Properties
Properties are guarded windows into an object's data: you can look at a value or change it, and the class can check the change first. It is like a receptionist who handles requests for the office.
In this page:
Syntax
class ClassName
{
public type AutoProperty { get; set; }
private type field;
public type PropertyName
{
get { return field; }
set { field = value; }
}
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Writing a property whose setter calls itself, such as
set { Name = value; }, causing infinite recursion. - Using a public field where a property with validation is needed.
- Forgetting
getorsetand then being unable to read or write the property.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: