On Tue, 28 Oct 2008 06:50:41 -0700 (PDT)
raylopez99 <(E-Mail Removed)> wrote:
>
> the "new" way (C#3):
>
> public string Name {get; set;}
>
> but what is not clear--is there a variable that's private named 'name'
> in the 'new' way? Hidden behind the scenes?
>
Such questions are often best dealt with by looking to the
authoritative source: the compiler itself. .NET makes this pretty easy.
Take the example C# source code:
======================================
using System;
public class ExampleProperties {
public static void Main() {
new ExampleProperties();
}
internal string Name {
get;
set;
}
public ExampleProperties() {
Name = "foo";
Console.WriteLine(Name);
}
}
======================================
Compile this to an assembly using the C# compiler, and take a look at
the disassembly of the IL; you can learn a lot about how the compiler
does things that way.
The output shows that there is a private string "<Name>k__BackingField"
contained within the class. There is also a set_Name(string) method
and a get_Name(string) method which modify the '<Name>k__BackingField".
If you modify it so that you have a private variable mName, and fill-in
the property to get and set it, the effect is the same, but you've
explicitly set the name of the property's internal variable.
> Second, why bother? how does this encapsulate anything? It seems you
> can just make Name public and be done with it.
Properties are part of the public interface for a class. Using a
empty, default property such as above makes the value available to
consumers of the class, while leaving the implementation details free
to you to figure out. Properties are, after all, nothing but veiled
method calls.
Say that you want to make it read-only? Remove the "set;".
Write-only? Do the inverse. Want to add some verification logic to
the setter? Okay, go ahead---create the private variable, fill in the
get using default behavior, and fill in the logic for the set method.
Want to add something extra to the returned value later on? Modify the
"get" routine to do it for you. Want to make it something dynamic
altogether? Use the default for a stub, and fill in the logic later.
There are many, many uses.
--- Mike
--
My sigfile ran away and is on hiatus.
http://www.trausch.us/