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#.
- To qualify members hidden by similar name
- To have an object pass itself as a parameter to other methods
- To have an object return itself from a method
- To declare indexers
- To declare extension methods
- To pass parameters between constructors
- To internally reassign value type (struct) value.
- To invoke an extension method on the current instance
- To cast itself to another type
- 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