Auto-implemented properties let you quickly create properties without writing extra code for storing values. They make your code shorter and easier to read.
0
0
Auto-implemented properties in C Sharp (C#)
Introduction
When you want to store simple data in a class without extra logic.
When you need a property to get and set values quickly.
When you want to keep your class code clean and simple.
When you don't need to customize how the property works.
Syntax
C Sharp (C#)
public type PropertyName { get; set; }The compiler creates a hidden variable to hold the value.
You can make properties read-only by using only get; without set;.
Examples
A simple property to store a name as text.
C Sharp (C#)
public string Name { get; set; }A property where other classes can read the age but only this class can change it.
C Sharp (C#)
public int Age { get; private set; }
A read-only property with a default value set to true.
C Sharp (C#)
public bool IsActive { get; } = true;
Sample Program
This program creates a Person object with auto-implemented properties Name and Age. It sets values and prints them.
C Sharp (C#)
using System; class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { Person p = new Person(); p.Name = "Alice"; p.Age = 30; Console.WriteLine($"Name: {p.Name}"); Console.WriteLine($"Age: {p.Age}"); } }
OutputSuccess
Important Notes
Auto-implemented properties simplify code but you cannot add extra logic directly inside them.
If you need to run code when getting or setting, use full property syntax instead.
Summary
Auto-implemented properties save time by creating hidden storage automatically.
They are great for simple data without extra rules.
You can control access by changing get and set visibility.