Computed properties let you create values that are calculated from other data automatically. They help keep your code clean and easy to understand.
0
0
Computed properties in C Sharp (C#)
Introduction
When you want to show a value that depends on other values, like a full name from first and last names.
When you want to avoid storing extra data that can be calculated on the fly.
When you want to keep your data safe and only allow reading a value, not changing it directly.
When you want to update a value automatically when related data changes.
Syntax
C Sharp (C#)
public ReturnType PropertyName { get { // return computed value here } set { // optional: update related data here } }
The get block calculates and returns the value.
The set block is optional and lets you update other data when the property is assigned.
Examples
This computed property returns the full name by joining first and last names.
C Sharp (C#)
public string FullName { get { return FirstName + " " + LastName; } }
Using expression-bodied syntax to compute area from width and height.
C Sharp (C#)
public int Area { get => Width * Height; }
This property controls setting age only if the value is not negative.
C Sharp (C#)
private int _age; public int Age { get => _age; set { if (value >= 0) _age = value; } }
Sample Program
This program creates a Person with first and last names. The FullName computed property joins them and prints the full name.
C Sharp (C#)
using System; class Person { public string FirstName { get; set; } public string LastName { get; set; } public string FullName { get => FirstName + " " + LastName; } } class Program { static void Main() { var person = new Person { FirstName = "Jane", LastName = "Doe" }; Console.WriteLine(person.FullName); } }
OutputSuccess
Important Notes
Computed properties do not store data themselves; they calculate values when accessed.
You can make a property read-only by only providing a get accessor.
Use computed properties to keep your data consistent and avoid duplication.
Summary
Computed properties calculate values based on other data automatically.
They help keep code clean by avoiding extra stored data.
You can make properties read-only or control how values are set.