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#.

  1. to qualify members hidden similar name
  2. to have object pass parameter other methods
  3. to have object return 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 extension method on current instance
  9. to cast type
  10. 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

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -