Q:

Understanding Get and Set Accessors

I'm a newbie and I'm trying to learn the basics of C#. This might sound quite trivial and may be stupid but its a doubt. While going through one of the source codes of an application, I saw a piece of code inside a class
private string fname;
public string FirstName
{
    get
    {
       return fname
    }
    set
    {
       fname = value;
    }
}

Can anyone tell me what it means. I understand that when we declare a class we access fname using an alias FirstName. If it's for some security purpose then what?

A:

This code is also equivalent to:
public string FirstName { get; set; }

What this do is define a property. In C# properties provide encapsulation for private fields.

A:

You can write your custom logic on your property. F.e, some validation:
public string FirstName
{
    get
    {
       return fname;
    }
    set
    {
       if (value.Count(s => Char.IsDigit(s)) > 0)
       {
           throw new Exception("Only letters allowed");
       }
       fname = value;
    }
}

