The this Keyword

Question
What’s the best way to use the this keyword in C#?

Answer
Avoid using this to reference a field or property unless it makes the code clearer.

Comment
There is an exception, of course. Using this is okay in a method or constructor that contains a parameter or local variable whose name resembles a class-level field or property.

Example

class Car {
    // In a real-world app, these would be properties.
    public string Make;
    public string Model;

    public Car(string make, string model) {
        this.Make = make;
        this.Model = model;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s