I am learning ASP.NET MVC and I can read English documents, but I don't really understand what is happening in this code:
public class Genre
{
public string Name { get; set; }
}
What does this mean: { get; set; }?
It's a so-called auto property, and is essentially a shorthand for the following (similar code will be generated by the compiler):
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
So as I understand it { get; set; } is an "auto property" which just like #Klaus and #Brandon said is shorthand for writing a property with a "backing field." So in this case:
public class Genre
{
private string name; // This is the backing field
public string Name // This is your property
{
get => name;
set => name = value;
}
}
However if you're like me - about an hour or so ago - you don't really understand what properties and accessors are, and you don't have the best understanding of some basic terminologies either. MSDN is a great tool for learning stuff like this but it's not always easy to understand for beginners. So I'm gonna try to explain this more in-depth here.
get and set are accessors, meaning they're able to access data and info in private fields (usually from a backing field) and usually do so from public properties (as you can see in the above example).
There's no denying that the above statement is pretty confusing, so let's go into some examples. Let's say this code is referring to genres of music. So within the class Genre, we're going to want different genres of music. Let's say we want to have 3 genres: Hip Hop, Rock, and Country. To do this we would use the name of the Class to create new instances of that class.
Genre g1 = new Genre(); //Here we're creating a new instance of the class "Genre"
//called g1. We'll create as many as we need (3)
Genre g2 = new Genre();
Genre g3 = new Genre();
//Note the () following new Genre. I believe that's essential since we're creating a
//new instance of a class (Like I said, I'm a beginner so I can't tell you exactly why
//it's there but I do know it's essential)
Now that we've created the instances of the Genre class we can set the genre names using the 'Name' property that was set way up above.
public string Name //Again, this is the 'Name' property
{ get; set; } //And this is the shorthand version the process we're doing right now
We can set the name of 'g1' to Hip Hop by writing the following
g1.Name = "Hip Hop";
What's happening here is sort of complex. Like I said before, get and set access information from private fields that you otherwise wouldn't be able to access. get can only read information from that private field and return it. set can only write information in that private field. But by having a property with both get and set we're able do both of those functions. And by writing g1.Name = "Hip Hop"; we are specifically using the set function from our Name property
set uses an implicit variable called value. Basically what this means is any time you see "value" within set, it's referring to a variable; the "value" variable. When we write g1.Name = we're using the = to pass in the value variable which in this case is "Hip Hop". So you can essentially think of it like this:
public class g1 //We've created an instance of the Genre Class called "g1"
{
private string name;
public string Name
{
get => name;
set => name = "Hip Hop"; //instead of 'value', "Hip Hop" is written because
//'value' in 'g1' was set to "Hip Hop" by previously
//writing 'g1.Name = "Hip Hop"'
}
}
It's Important to note that the above example isn't actually written in the code. It's more of a hypothetical code that represents what's going on in the background.
So now that we've set the Name of the g1 instance of Genre, I believe we can get the name by writing
console.WriteLine (g1.Name); //This uses the 'get' function from our 'Name' Property
//and returns the field 'name' which we just set to
//"Hip Hop"
and if we ran this we would get "Hip Hop" in our console.
So for the purpose of this explanation I'll complete the example with outputs as well
using System;
public class Genre
{
public string Name { get; set; }
}
public class MainClass
{
public static void Main()
{
Genre g1 = new Genre();
Genre g2 = new Genre();
Genre g3 = new Genre();
g1.Name = "Hip Hop";
g2.Name = "Rock";
g3.Name = "Country";
Console.WriteLine ("Genres: {0}, {1}, {2}", g1.Name, g2.Name, g3.Name);
}
}
Output:
"Genres: Hip Hop, Rock, Country"
Those are automatic properties
Basically another way of writing a property with a backing field.
public class Genre
{
private string _name;
public string Name
{
get => _name;
set => _name = value;
}
}
It is a shortcut to expose data members as public so that you don't need to explicitly create a private data members. C# will creates a private data member for you.
You could just make your data members public without using this shortcut but then if you decided to change the implementation of the data member to have some logic then you would need to break the interface. So in short it is a shortcut to create more flexible code.
This is the short way of doing this:
public class Genre
{
private string _name;
public string Name
{
get => _name;
set => _name = value;
}
}
Basically, it's a shortcut of:
class Genre{
private string genre;
public string getGenre() {
return this.genre;
}
public void setGenre(string theGenre) {
this.genre = theGenre;
}
}
//In Main method
genre g1 = new Genre();
g1.setGenre("Female");
g1.getGenre(); //Female
Basically it helps to protect your data. Consider this example without setters and getter and the same one with them.
Without setters and getters
Class Student
using System;
using System.Collections.Generic;
using System.Text;
namespace MyFirstProject
{
class Student
{
public string name;
public string gender;
public Student(string cName, string cGender)
{
name = cName;
gender= cGender;
}
}
}
In Main
Student s = new Student("Some name", "Superman"); //Gender is superman, It works but it is meaningless
Console.WriteLine(s.Gender);
With setters and getters
using System;
using System.Collections.Generic;
using System.Text;
namespace MyFirstProject
{
class Student
{
public string name;
private string gender;
public Student(string cName, string cGender)
{
name = cName;
Gender = cGender;
}
public string Gender
{
get { return gender; }
set
{
if (value == "Male" || value == "Female" || value == "Other")
{
gender = value;
}
else
{
throw new ArgumentException("Invalid value supplied");
}
}
}
}
}
In Main:
Student s = new Student("somename", "Other"); // Here you can set only those three values otherwise it throws ArgumentException.
Console.WriteLine(s.Gender);
Its an auto-implemented property for C#.
The get/set pattern provides a structure that allows logic to be added during the setting ('set') or retrieval ('get') of a property instance of an instantiated class, which can be useful when some instantiation logic is required for the property.
A property can have a 'get' accessor only, which is done in order to make that property read-only
When implementing a get/set pattern, an intermediate variable is used as a container into which a value can be placed and a value extracted. The intermediate variable is usually prefixed with an underscore.
this intermediate variable is private in order to ensure that it can only be accessed via its get/set calls. See the answer from Brandon, as his answer demonstrates the most commonly used syntax conventions for implementing get/set.
They are the accessors for the public property Name.
You would use them to get/set the value of that property in an instance of Genre.
That is an Auto-Implemented Property. It's basically a shorthand way of creating properties for a class in C#, without having to define private variables for them. They are normally used when no extra logic is required when getting or setting the value of a variable.
You can read more on MSDN's Auto-Implemented Properties Programming Guide.
This mean that if you create a variable of type Genre, you will be able to access the variable as a property
Genre oG = new Genre();
oG.Name = "Test";
In the Visual Studio, if you define a property X in a class and you want to use this class only as a type, after building your project you will get a warning that says "Field X is never assigned to, and will always has its default value".
By adding a { get; set; } to X property, you will not get this warning.
In addition in Visual Studio 2013 and upper versions, by adding { get; set; } you are able to see all references to that property.
Its basically a shorthand. You can write public string Name { get; set; } like in many examples, but you can also write it:
private string _name;
public string Name
{
get { return _name; }
set { _name = value ; } // value is a special keyword here
}
Why it is used? It can be used to filter access to a property, for example you don't want names to include numbers.
Let me give you an example:
private class Person {
private int _age; // Person._age = 25; will throw an error
public int Age{
get { return _age; } // example: Console.WriteLine(Person.Age);
set {
if ( value >= 0) {
_age = value; } // valid example: Person.Age = 25;
}
}
}
Officially its called Auto-Implemented Properties and its good habit to read the (programming guide).
I would also recommend tutorial video C# Properties: Why use "get" and "set".
Such { get; set; } syntax is called automatic properties, C# 3.0 syntax
You must use Visual C# 2008 / csc v3.5 or above to compile.
But you can compile output that targets as low as .NET Framework 2.0 (no runtime or classes required to support this feature).
Get set are access modifiers to property.
Get reads the property field.
Set sets the property value.
Get is like Read-only access.
Set is like Write-only access.
To use the property as read write both get and set must be used.
Get is invoked when the property appears on the right-hand side (RHS)
Set is invoked when the property appears on the left-hand side (LHS)
of '=' symbol
For an auto-implemented property, the backing field works behind the scene and not visible.
Example:
public string Log { get; set; }
Whereas for a non auto-implemented property the backing field is upfront, visible as a private scoped variable.
Example:
private string log;
public string Log
{
get => log;
set => log = value;
}
Also, it is worth noted here is the 'getter' and 'setter' can use the different 'backing field'
A property is a like a layer that separates the private variable from other members of a class. From outside world it feels like a property is just a field, a property can be accessed using .Property
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName => $"{FirstName} {LastName}";
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return $"{FirstName} {LastName}"; } }
}
FullName is a Property. The one with arrow is a shortcut. From outside world, we can access FullName like this:
var person = new Person();
Console.WriteLine(person.FullName);
Callers do not care about how you implemented the FullName. But inside the class you can change FullName whatever you want.
Check out Microsoft Documentation for more detailed explanation:
https://learn.microsoft.com/en-us/dotnet/csharp/properties
Define the Private variables
Inside the Constructor and load the data
I have created Constant and load the data from constant to Selected List class.
public class GridModel
{
private IEnumerable<SelectList> selectList;
private IEnumerable<SelectList> Roles;
public GridModel()
{
selectList = from PageSizes e in Enum.GetValues(typeof(PageSizes))
select( new SelectList()
{
Id = (int)e,
Name = e.ToString()
});
Roles= from Userroles e in Enum.GetValues(typeof(Userroles))
select (new SelectList()
{
Id = (int)e,
Name = e.ToString()
});
}
public IEnumerable<SelectList> Pagesizelist { get { return this.selectList; } set { this.selectList = value; } }
public IEnumerable<SelectList> RoleList { get { return this.Roles; } set { this.Roles = value; } }
public IEnumerable<SelectList> StatusList { get; set; }
}
Properties are functions that are used to encapsulate data, and allow additional code to be executed every time a value is retrieved or modified.
C# unlike C++, VB.Net or Objective-C doesn’t have a single keyword for declaring properties, instead it uses two keywords (get/set) to give a much abbreviated syntax for declaring the functions.
But it is quite common to have properties, not because you want to run additional code when data is retrieved or modified, but because either you MIGHT want to do so in the future or there is a contract saying this value has to be a exposed as a property (C# does not allow exposing data as fields via interfaces). Which means that even the abbreviated syntax for the functions is more verbose than needed. Realizing this, the language designers decided to shorten the syntax even further for this typical use case, and added “auto” properties that don’t require anything more than the bare minimum, to wit, the enclosing braces, and either of the two keywords (separated by a semicolon when using both).
In VB.Net, the syntax for these “auto” properties is the same length as in c# —- Property X as String vs string X {get; set;}, 20 characters in both cases. It achieves such succinctness because it actually requires 3 keyword under the normal case, and in the case of auto properties can do without 2 of them.
Removing any more from either, and either a new keyword would have had to be added, or significance attached to symbols or white space.
Related
I have requirement in a custom class where I want to make one of my properties required.
How can I make the following property required?
public string DocumentType
{
get
{
return _documentType;
}
set
{
_documentType = value;
}
}
If you mean "the user must specify a value", then force it via the constructor:
public YourType(string documentType) {
DocumentType = documentType; // TODO validation; can it be null? blank?
}
public string DocumentType {get;private set;}
Now you can't create an instance without specifying the document type, and it can't be removed after that time. You could also allow the set but validate:
public YourType(string documentType) {
DocumentType = documentType;
}
private string documentType;
public string DocumentType {
get { return documentType; }
set {
// TODO: validate
documentType = value;
}
}
.NET 7 or newer
Syntax
public class MyClass
{
public required string Name { get; init; }
}
new MyClass(); // illegal
new MyClass { Name = "Me" }; // works fine
Remarks
The required properties must declare a setter (either init or set).
Access modifiers on properties or setters cannot be less visible than their containing type, as they would make impossible to initialize the class in some cases.
public class MyClass
{
internal required string Name { get; set; } // illegal
}
Documentation
Official documentation here
Feature demo here
.NET 6 or older
See this answer
If you mean you want it always to have been given a value by the client code, then your best bet is to require it as a parameter in the constructor:
class SomeClass
{
private string _documentType;
public string DocumentType
{
get
{
return _documentType;
}
set
{
_documentType = value;
}
}
public SomeClass(string documentType)
{
DocumentType = documentType;
}
}
You can do your validation – if you need it – either in the property's set accessor body or in the constructor.
With the release of .NET 7 and C# 11 in November 2022 you can now use the required modifier this way:
public class Person
{
public Person() { }
[SetsRequiredMembers]
public Person(string firstName) => FirstName = firstName;
public required string FirstName { get; init; }
public int Age { get; set; }
}
And when you don't have the required properties it will throw an error when you try to initialize an object.
For more information refer to:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#required-members
https://learn.microsoft.com/en-us/dotnet/csharp/properties#init-only
Add a required attribute to the property
Required(ErrorMessage = "DocumentTypeis required.")]
public string DocumentType
{
get
{
return _documentType;
}
set
{
_documentType = value;
}
}
For custom attribute detail Click Here
I used an other solution, not exactly what you want, but worked for me fine because I declare the object first and based on specific situation I have different values. I didnt want to use the constructor because I then had to use dummy data.
My solution was to create Private Sets on the class (public get) and you can only set the values on the object by methods. For example:
public void SetObject(string mandatory, string mandatory2, string optional = "", string optional2 = "")
This one liner works in C# 9:
public record Document(string DocumentType);
new Document(); // compiler error
new Document("csv"); // correct way to construct with required parameter
This explains how it works. In the above code, Document is the name of the class or "record". That first line of code actually defines an entire class. In addition to this solution essentially making a required DocumentType property (required by an auto implemented constructor), because it uses records, there are additional implications. So this may not always be an appropriate solution, and the C# 11 required keyword will still come in handy at times. Just using record types doesn't automatically make properties required. The above code is a special syntax way of using records that essentially has this effect as well as making the property init only and causes a deconstructor to be automatically implemented.
A better example would be using an int property instead of a string since a string could still be empty. Unfortunately I don't know of any good way to do extra validation within the record to make sure the string is not empty or an int is in range, etc. You would have to go deeper down the TOP (type driven development) rabbit hole, which may not be a bad thing. You could create your own type that doesn't allow empty strings or integers outside your accepted range. Unfortunately such an approach would lead to runtime discovery of invalid input instead of compile time. There might be a better way using static analysis and metadata, but I've been away from C# for too long to know anything about that.
Usually I would build my field like this:
private string name;
public void setName(string name){
this.name = name;
}
public string getName(){
return name
}
that works perfectly when doing this: string myString = object.getName() or object.setName("Alex").
However, I thought I might give the inbuilt C# functions a try.
So I did this:
private string name { get; set; }
however, that won't work at all. When I try to access the field with object.name, I can't even access it due to private restriction.
Did I misunderstand something about these predefined get/sets?
If I had to mark every field as public, why should I even use getters or setters? I could access the field like in the snippet above without get and set?
You're mixing up way too many things - you might want to read a book on C#, really. It usually takes some time to get rid of some of the preconceptions from your old programming language - but you really do want to do that; even Java and C# are incredibly different when you go beyond the surface appearance.
First, nothing is forcing you to use auto-properties. If you want to use properties while keeping your manual backing fields, you can simply use this:
private string name;
public string Name { get { return name; } set { name = value; } }
If you do want to use auto-properties, you have to understand that the backing field is hidden - you're only declaring the property; and you want that property to be public (though you can also use accessibility modifiers on the individual get/set "methods", e.g. private set). But the field is never accessible - it's "always" behind the property.
To mirror your original code, this is what you want:
public string Name { get; set; }
Only if you ever need to move away from using auto-properties (that is, you need to add some logic to either the getter or the setter), you will have to reintroduce the manual backing field, and stop using auto-properties - see the first code sample in my answer.
Did I misunderstand something about these predefined get/sets?
Yes, you did. The property itself has to be public. If you're using auto-properties, then you can't do any validation since the backing field is compiler generated. If you want to actually do something with the value before, you can use a property with a backing field:
private string name;
public string Name
{
get { return name; }
set
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("name cannot be null");
name = value
}
}
Because this:
public string Name { get; set; }
Generated a backing field like this:
[DebuggerBrowsable(DebuggerBrowsableState.Never), CompilerGenerated]
private string <Name>k__BackingField;
public string Name
{
[CompilerGenerated]
get
{
return this.<Name>k__BackingField;
}
[CompilerGenerated]
set
{
this.<Name>k__BackingField = value;
}
}
Just do
public string Name { get; set; }
That compiles down to a private field with an unspeakable name, and a public property. That public property has a public get method and a public set method.
Seems to be exactly what you want.
Alternatively, use
public string Name { get; private set; }
Your get method will be public as before, but the set method will be private then.
As of C# 6 (Visual Studio 2015), you can even do
public string Name { get; }
In that case, there is no set method, not even a private one, but you can assign to the underlying field through the property in the constructor.
Did I misunderstand something about these predefined get/sets?
Yes, a bit.
If I had to mark every field as public, why should I even use getters or setters? I could access the field like in the snippet above without get and set?
This is the part that you're missing. The syntax you are talking about it called an auto-implemented property. That is, when you write:
public string Name { get; set; }
the C# compiler generates a private field, getter, and setter behind the scenes for you. You can see them if you look at the metadata for your class, and get access to them via reflection. They have the exact same names as the getter or setter you would write yourself (typically get_Name and set_Name). The only difference is, you didn't have to write them.
The reason to do this is because most getter/setter pairs only exist to add a layer of abstraction over a private field, and consist of a single return name or name = value line of code. If that's all you want, you may as well let the compiler write it for you.
However, if you ever needed something more complex, you can manually implement the getter and setter yourself, and callers won't know the difference. In other words, if you change:
public string Name { get; set; }
to
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
RecalculateSomeStuff();
}
}
then the metadata for your class is identical. Anyone using your class does not have to even be recompiled to pick up the new setter, because as far as the callers are concerned, they're still called set_Name directly.
What the others want to tell you is that you should deferentiate between fields (privates) and properties (public) (is not a rule but a convention)
private string name;
public string Name{ get; set;}
// you can acces to the property:
var objectName = YourObject.Name
// and set the value of your property:
YourObject.Name = "whatever"
First of all the equivalent of your code is
private string _name;
public string Name
{
get {return _name;}
set { _name = value; }
}
OR simply
public string Name { get; set; }
To define the accessibility level of the "Name" field, you put the access modifiers (public, protected, etc.) before get or set
Example
//Read only properties
public string Name
{
get {return _name;}
private set { _name = value; }
}
To have more details and see difference between public fieal and public property see Difference between Auto - Implemented Properties and normal public member
PS :
To write this in Visual studio you can use snippet, type prop keyword then tab key or propfull and press tab key. press tab key our shift+tab to navigate between highlighted fields
I'm going to build my MVC Web Application and I created my data models.
I found online many ways to compile a data model code. This is easiest one, using only public properties:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
But I also found a version using a private variable and a public properies, like this:
public class Person
{
private int id;
private string firstName;
private string lastName;
public int Id { get { return id; } set { id = value; } }
public string FirstName { get { return firstName; } set { firstName = value; } }
public string LastName { get { return lastName; } set { lastName = value; } }
}
What is the difference between these two data models?
When is more advisable using the first one or the second one?
This is the same like asking: what is a difference bwteen auto properties and normal properties.
Auto properties:
easy creation (less to type)
internal field is generated for you automatically by compiler
Not possible to debug (set a break point inside the property)
Normal properties
Sligtly more code to type
Easy to debug
More code can be injected inside get and set
If first example compiler will create private field for every automatic property itself, but they behave exactly the same. More info on MSDN
I would suggest second approach as you have more control how property works, but there is nothing wrong in using first one.
The fiest block you have are auto-properties, and under the hood the c# will be compiled similar to the second block, so in this case there is no difference. Take a look at these posts here:
C# 3.0 auto-properties - useful or not?
What are Automatic Properties in C# and what is their purpose?
Any reason to use auto-implemented properties over manual implemented properties?
If you were implementing the INotifyPropertyChanged interface, then you would need to use the traditional way as you would be interacting with the property in the setter, see example...
http://msdn.microsoft.com/en-us/library/ms743695.aspx
New to C#, and I understand that encapsulation is just a way of "protecting data". But I am still unclear. I thought that the point of get and set accessors were to add tests within those methods to check to see if parameters meet certain criteria, before allowing an external function to get and set anything, like this:
private string myName;
public string MyName;// this is a property, speical to c#, which sets the backing field.
private string myName = "mary";// the backing field.
public string MyName // this is a property, which sets/gets the backing field.
{
get
{
return myName;
}
set
{
if (value != "Silly Woman"){
myName = value;
}
}
}
But I've been seeing code in c# which just looks like this:
public string MyName { get; set; }
Why would you just have a get and set with nothing in there, - isn't that the same as just declaring your private backing field public? If you can just get and set it from outside, why wouldn't you just do it directly?
Indeed, creating an auto-property as follows:
public string Name { get; set; }
is identical to building a property backed by a field:
private string _name;
public string Name {
get { return _name; }
set { _name = value; }
}
The point of these properties is not to hide data. As you observed, they don't do this. Instead, these properties can do other stuff instead of just working with a field:
public string Name {
get { return _name; }
set { if (value == null) throw new Exception("GTFO!"); _name = value; }
}
Another thing is, you can make properties virtual:
public virtual string Name { get; set; }
which, if overridden, can provide different results and behaviours in a derived class.
By using public string MyName { get; set; }, you leave an ability to change its logic later without the need to recompile/change other code that uses your property.
For example, if you are making a library and v1 uses a field and v2 uses a property, applications that work with v1 will not work with v2 without recompilation (and, potentially, code changes if they are written in some .NET language that has different syntax for accessing fields).
Another important difference is in serialization scenarios -- a lot of them do not support fields. Also any interface that requires a property can not be implemented without using one, but depending on interface it may not be required to do any additional checks/logic in it.
It makes it easier to add logic later. If you have a class that has a public field that you want to change to a property, you have to recompile everything that uses your class. That's a key point that I didn't understand initially.
If you have a class:
public class MyClass
{
public string MyString;
}
You could access the value like this:
var myClass = new MyClass();
string s = myClass.MyString;
Now change that to a property:
public class MyClass
{
public string MyString { get; set; }
}
How is it accessed? The exact same way:
var myClass = new MyClass();
string s = myClass.MyString;
So no big deal, right? Well, actually....
Properties are actually compiled into getter and setter methods:
get_MyString() and set_MyString(string value)
So the two methods do produce different compiled code. Now if all your code that uses this class is in the same project, is not as big a deal, because it will all be compiled together. But if you have an API library that you've distributed, it can be a much bigger deal to update.
Because it is easier to change the Code if you want to add the checks/tests later on.
Especially if you have many inheritance and many classes in your code it is very hard to change the implementation from a public variable to a public Property.
Moreover you can add to the get and set within the property different attributes, e.g. if you are using reflection. The get and set of the property are internally different methods. If you have just a public variable /field it is not possible to added different properties to the different access ways.
Yeah, but you can easily change it to:
public string MyName { get; private set; }
Plus, properties are used in other scenarios, like DataContracts and Serialization... so, this is a nice feature... (Mostly, syntactic sugar. I think) EDIT: I take that back.. you can apply virtual to it, so it's not the same
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
It's called Properties (MSDN article). The reason for using them is to encapsulate accessing some class field to be able to easily change class behavior in future if needed.
This is also equivalent to so called auto-property, since the property at this moment oftimedoes not add any logic:
public string FirstName { get; set; }
get and set methods are called accessors(getters) and mutators(setters) these methods are used to access and mutate the attributes of an object without allowing the access from outside the class.
See that access modifier of the variable fname is private which means it can only be accessed by any method inside the class.
and note that the get and set methods should normally be given the public access modifier which enables the method to be accessed from any outside class.