C# properties
-
Hi, If we use Properties in our Class we would need one "local" variable to actually hold the value and one to actually be accessed from the outside... private string name; // local public string Name // access outside { get { return name; } set { name = value; } } So basically my question is... are there TWO variables or only ONE... Is the public one just for asthetic reasons? If there are two it would be wasting space everytime we use a Property wouldn't it? Also the "value" parameter - is that always assumed in Properties, cause I don't see any explicit mention of it anywhere? Thanks. Mohnish
-
Hi, If we use Properties in our Class we would need one "local" variable to actually hold the value and one to actually be accessed from the outside... private string name; // local public string Name // access outside { get { return name; } set { name = value; } } So basically my question is... are there TWO variables or only ONE... Is the public one just for asthetic reasons? If there are two it would be wasting space everytime we use a Property wouldn't it? Also the "value" parameter - is that always assumed in Properties, cause I don't see any explicit mention of it anywhere? Thanks. Mohnish
I think ONE. ( may be this approach can help us) As we know , this the way of accessing member variables( state of the class) through methods(get,set) without breaking the client code. Often memeber variables (State) need to be computed.(ex: get and set to/from DB),then this way of accessing will be useful. I think this the trade-off.(If we really wasting space) Check your MSIL using ILDASM.exe( NET FWk/SDK/ bin). in your example, NAME is property and name is member variable. Next, value is implicit parameter for "set" method CLR reads your program as set(value) { membervariable = value; } Thanks, Anand.
-
Hi, If we use Properties in our Class we would need one "local" variable to actually hold the value and one to actually be accessed from the outside... private string name; // local public string Name // access outside { get { return name; } set { name = value; } } So basically my question is... are there TWO variables or only ONE... Is the public one just for asthetic reasons? If there are two it would be wasting space everytime we use a Property wouldn't it? Also the "value" parameter - is that always assumed in Properties, cause I don't see any explicit mention of it anywhere? Thanks. Mohnish
In your example there is only ONE real member variable: name. Indeed, "Name" just exists just for aesthetic reasons. Your example doesn't yet show the advantages of using Properties. These arise if you add e.g. bounds-checking code to your get and/or set accessors. Sito Dekker