c# - Is it better to use this. before code? -


i need go online , find tutorial something. finding people put code this:

this.button1.text = "random text"; 

then find code this:

button1.text = "random text"; 

is better use this.whatever or not matter?

this make clear, in cases have use this:

  1. differentiate between parameter , local member:

    //local member object item; private void somemethod(object item){     this.item = item;//must use } 
  2. pass current class instance method:

    public class someclass {   private void somemethod(someclass obj){      //....   }   private void anothermethod(){     somemethod(this);//pass current instance somemethod     //.....   } } 
  3. use in extension methods:

    public static class someclassextension {     public static void someclassmethod(this someclass obj){         //use obj reference object calling method...     } } 
  4. call constructor constructor (with different signature):

    public form1(string s) : this() {//call form1() before executing other code in form1(string s)    //...... } 
  5. use declaring indexers:

    public class someclass {    //declare index returning string    public string this[int index] {       {return ...}       set { ... }    } } 
  6. use auto-properties in struct:

    public struct somestruct {    public object autoprop1 {get;set;}    public object autoprop2 {get;set;}    public somestruct() : this() //must use    {       autoprop1 = someobject;       autoprop2 = someobject;    } } 
  7. cast current instance based classes/types:

    public class classb : classc {     //... } public class classa : classb {     public classa(){        ((classc)this).memberofclassc ... ;//there might member in classc        //which overridden in classa or classb, casting classc can invoke original member instead of overridden one.     } } 

there might other uses of this, i'll update later if think out.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -