Click here to Skip to main content
15,905,229 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey guys,

I got this code here:

C#
private string _firstName;


    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }

    }


But i don't get how it work I tried to play around with it. I'm assuming that it means if I put a value in the private object named _firstName I can use it inside the public object FirstName even if it's private.

Anyone?
Posted

The private string is a backing field that is set when you do FirstName = "...." in your code. Effectively what happens is that this code translates into a hidden set call (that's what the compiler does under the surface). The pseudo-logic looks like this:
C#
public void FirstName_Set(string value)
{
  _firstName = value;
}
By doing this, we ensure that _firstName is hidden from outside classes (we encapsulate it). Of course, if all you are doing is setting a simple value and you aren't doing anything like serialization or more complex forms of validation, then you might as well just have
C#
public string FirstName;
 
Share this answer
 
v2
Comments
KatsuneShinsengumi 27-Jan-14 9:55am    
One more question, what does the code "value" do? Sorry I'd just started ASP.NET and C# like last week.
Pete O'Hanlon 27-Jan-14 10:02am    
You can think of "value" as being a magic variable - it's automatically applied to the set part of a property to pass in the value. I have updated my pseudo-logic to show you where it appears.
KatsuneShinsengumi 27-Jan-14 10:10am    
Thanks, although the changes gets me confused, your original post gives me the idea of it's purpose.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900