Auto-Implemented Properties
Declare properties with concise auto syntax.
What Is a Property?
A property looks like a field from the outside but is backed by accessor methods (get and set). Properties let you expose data while keeping control over how it is read and written.
using System;
class Program
{
public string Name { get; set; }
static void Main()
{
var p = new Program();
p.Name = "Coddy";
Console.WriteLine(p.Name);
}
}Auto-Implemented Syntax
An auto-implemented property uses { get; set; }. The compiler generates a hidden backing field for you, so you do not write one by hand.
using System;
class Person
{
public string FirstName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
var person = new Person { FirstName = "Ada", Age = 36 };
Console.WriteLine(person.FirstName + " is " + person.Age);
}
}All lessons in this course
- Auto-Implemented Properties
- Full Properties with Backing Fields
- Expression-Bodied Members
- Indexers