{ get; set; }
-
from time to time, I see some sample code that is handed to me that has a code snippet that looks like this:
public string Name { get; set; }
Does this actually do anything? Does it really make it so that one can set and get the "Name" string variable? I have always thought that what is required is something like this:private string name; public string Name { get { return this.name; } set { this.name = value; } }
Am I correct? Please advise. -
from time to time, I see some sample code that is handed to me that has a code snippet that looks like this:
public string Name { get; set; }
Does this actually do anything? Does it really make it so that one can set and get the "Name" string variable? I have always thought that what is required is something like this:private string name; public string Name { get { return this.name; } set { this.name = value; } }
Am I correct? Please advise.Yes, they are [Auto-Implemented Properties (C# Programming Guide) | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties). They basically do the same thing as you're used to writing by hand, but with a field that has some compiler-generated name which is not a legal identifier in C# so you cannot accidentally (nor on purpose) refer to the backing field directly.
-
from time to time, I see some sample code that is handed to me that has a code snippet that looks like this:
public string Name { get; set; }
Does this actually do anything? Does it really make it so that one can set and get the "Name" string variable? I have always thought that what is required is something like this:private string name; public string Name { get { return this.name; } set { this.name = value; } }
Am I correct? Please advise. -
from time to time, I see some sample code that is handed to me that has a code snippet that looks like this:
public string Name { get; set; }
Does this actually do anything? Does it really make it so that one can set and get the "Name" string variable? I have always thought that what is required is something like this:private string name; public string Name { get { return this.name; } set { this.name = value; } }
Am I correct? Please advise.Generally, in c# Property is an extension of class variable and it provides a mechanism to read, write or change the value of class variable without effecting the external way of accessing it in our applications. check properties in c#, it will help you to understand why we required to use properties (get, set) in c#.