Why is "this.SomeVar" used in C# wont "SomeVar" work?
-
I notice in a lot of C# code that "this.SomeVar" is used when the "SomeVar" could be called directly. I removed the "this." from a WebApplication and it seemed to work OK :) What is it doing and why is it here? Is it the same as the C++ "this->"? Thanks Note I only used C# for a day so if this is a stupid question I am sorry.:confused:
-
I notice in a lot of C# code that "this.SomeVar" is used when the "SomeVar" could be called directly. I removed the "this." from a WebApplication and it seemed to work OK :) What is it doing and why is it here? Is it the same as the C++ "this->"? Thanks Note I only used C# for a day so if this is a stupid question I am sorry.:confused:
My code looks like this (before cleaning, anyway) because I usually manage to forget the names of member variables. Typing "this." brings up a list of member variables, letting me search for my member variable's name without having to change my place in the code. So, short answer - laziness - at least in my case :) -- Russell Morris Georgia Institute of Technology "Lisa, just because I don't care doesn't mean I'm not listening..." - Homer
-
I notice in a lot of C# code that "this.SomeVar" is used when the "SomeVar" could be called directly. I removed the "this." from a WebApplication and it seemed to work OK :) What is it doing and why is it here? Is it the same as the C++ "this->"? Thanks Note I only used C# for a day so if this is a stupid question I am sorry.:confused:
Hi! The [this] keyword is used so that you can refer to a member variable instance without accidently calling another variable by the same name. Take this example: class MyExample { private string value = ""; public string Text { get { return this.value; } set { this.value = value; } } } Now personally I would not have written code like this, but there could be a time when something similar occurs. In this example, value is the variable name sent in though the Text Property and can't be renamed. Since I have an internat member called value, the only way that I can communicate with it is with the [this] call, which tells the compiler you were talking about the global instance and not the system local instance. Using the [this] statement is not required by any means, but can help tell other developers that you are: A. Using a member property and B. There can not be a conflict in local naming. I hope this helps. ;P -V-