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:
- differentiate between - parameter,- local member:- //local member object item; private void somemethod(object item){ this.item = item;//must use }
- pass current class instance method: - public class someclass { private void somemethod(someclass obj){ //.... } private void anothermethod(){ somemethod(this);//pass current instance somemethod //..... } }
- use in extension methods: - public static class someclassextension { public static void someclassmethod(this someclass obj){ //use obj reference object calling method... } }
- call constructor constructor (with different signature): - public form1(string s) : this() {//call form1() before executing other code in form1(string s) //...... }
- use declaring indexers: - public class someclass { //declare index returning string public string this[int index] { {return ...} set { ... } } }
- 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; } }
- 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
Post a Comment