c# - When do you use the "this" keyword? -
i curious how other people use this keyword. tend use in constructors, may use throughout class in other methods. examples:
in 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); }
there several usages of this keyword in c#.
- to qualify members hidden similar name
- to have object pass parameter other methods
- to have object return method
- to declare indexers
- to declare extension methods
- to pass parameters between constructors
- to internally reassign value type (struct) value.
- to invoke extension method on current instance
- to cast type
- to chain constructors defined in same class
you can avoid first usage not having member , local variables same name in scope, example following common naming conventions , using properties (pascal case) instead of fields (camel case) avoid colliding local variables (also camel case). in c# 3.0 fields can converted properties using auto-implemented properties.
Comments
Post a Comment