Properties
In this page:
Properties
Properties expose a class's data through get and set accessors, giving you control over how a field is read or written while still looking like a plain field to callers. Auto-implemented properties ({ get; set; }) skip the backing field entirely for simple cases. Properties are the idiomatic C# alternative to writing manual getter/setter methods.
Note: Use { get; private set; } to make a property publicly readable but only settable from inside the class.
Example: Properties
using System;
class Product
{
public string Name { get; set; }
private decimal price;
public decimal Price
{
get { return price; }
set { price = value < 0 ? 0 : value; }
}
}
class Program
{
static void Main(string[] args)
{
Product p = new Product { Name = "Pen", Price = -5 };
Console.WriteLine($"{p.Name}: {p.Price}");
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: