Auto properties are a shorthand syntax for defining properties in C#. Instead of explicitly defining a private backing field and the get/set methods for a property, an auto property allows the compiler to automatically generate the backing field and default get/set methods.
Here’s an example of an auto property:
public class Person
{
public string Name { get; set; }
}
In this example, the Name
property is defined as an auto property. The get
and set
methods are automatically generated by the compiler, and there is no explicit backing field. This allows us to easily get and set the Name
property on a Person
object, like this:
var person = new Person();
person.Name = "John";
Console.WriteLine(person.Name); // Output: "John"
We can also provide an initial value for an auto property:
public class Person
{
public string Name { get; set; } = "Unknown";
}
In this example, the Name
property is initialized to "Unknown"
by default.
We can also make an auto property read-only by omitting the set
method:
public class Person
{
public string Name { get; }
}
In this example, the Name
property can only be set in the constructor of the Person
class, but it can be read from anywhere:
var person = new Person("John");
Console.WriteLine(person.Name); // Output: "John"