Wednesday, September 26, 2018

c# - When do you use the "this" keyword?




I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:



In a constructor:




public Light(Vector v)
{
this.dir = new Vector(v);
}


Elsewhere



public void SomeMethod()
{

Vector vec = new Vector();
double d = (vec * vec) - (this.radius * this.radius);
}

Answer



There are several usages of this keyword in C#.




  1. To qualify members hidden by similar name

  2. To have an object pass itself as a parameter to other methods


  3. To have an object return itself from a method

  4. To declare indexers

  5. To declare extension methods

  6. To pass parameters between constructors

  7. To internally reassign value type (struct) value.

  8. To invoke an extension method on the current instance

  9. To cast itself to another type

  10. To chain constructors defined in the same class




You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...