Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Get and Set Accessors

Tags:

c#

asp.net

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?

like image 402
iJade Avatar asked Mar 17 '13 16:03

iJade


3 Answers

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.

like image 110
Darin Dimitrov Avatar answered Oct 13 '22 22:10

Darin Dimitrov


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;
    }
}
like image 21
Farhad Jabiyev Avatar answered Oct 13 '22 21:10

Farhad Jabiyev


fname is a field and has private visibility but FirstName is a public property therefore it will be visible outside of the class and can contain logic inside get and set methods

like image 38
syned Avatar answered Oct 13 '22 22:10

syned