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?
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
.
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;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With