In C#, properties are an essential part of encapsulation and data access within classes. Among various types of properties, computed properties stand out for their ability to calculate a value dynamically, based on other fields or properties. This document provides a comprehensive explanation of computed properties in C#, including their syntax, benefits, use cases, and practical examples.
A computed property in C# is a property whose value is calculated dynamically when the get accessor is called. Unlike traditional properties that return a stored value from a field, computed properties perform operations or logic to determine the value at runtime.
public class Rectangle
{
public double Width { get; set; }
public double Height { get; set; }
public double Area
{
get { return Width * Height; }
}
}
In the above example, Area is a computed property because its value is calculated from the Width and Height properties rather than being stored directly.
Most computed properties only implement the get accessor since the value is determined dynamically.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get { return $"{FirstName} {LastName}"; }
}
}
This approach avoids duplicating name logic and ensures that FullName always reflects the current values of FirstName and LastName.
Computed properties can include control statements to calculate a value based on various conditions.
public class Applicant
{
public int Age { get; set; }
public bool HasCriminalRecord { get; set; }
public bool IsEligible
{
get
{
return Age >= 18 && !HasCriminalRecord;
}
}
}
Here, IsEligible checks for multiple conditions to determine the result dynamically.
Starting from C# 6.0, you can simplify computed properties using the expression-bodied syntax.
public string FullName => $"{FirstName} {LastName}";
This syntax is concise and ideal for simple one-line computed properties.
public class Circle
{
public double Radius { get; set; }
public double Circumference => 2 * Math.PI * Radius;
}
Expression-bodied syntax reduces boilerplate and enhances readability for simple calculations.
In some cases, a computed property might work in conjunction with backing fields, either for caching purposes or to include a set accessor.
public class Weather
{
private double _celsius;
public double Celsius
{
get { return _celsius; }
set { _celsius = value; }
}
public double Fahrenheit
{
get { return (_celsius * 9 / 5) + 32; }
}
}
This demonstrates a one-way conversion from Celsius to Fahrenheit using a computed property.
Although most computed properties are read-only, you can also use computed logic in the set accessor.
public class Person
{
public DateTime DateOfBirth { get; set; }
public int Age
{
get
{
var today = DateTime.Today;
int age = today.Year - DateOfBirth.Year;
if (DateOfBirth.Date > today.AddYears(-age)) age--;
return age;
}
}
}
The Age is always computed based on DateOfBirth and the current date.
In performance-sensitive applications, recomputing the same value can be expensive. In such cases, caching the computed value can be useful.
public class Report
{
private List _data;
private double? _average;
public Report(List data)
{
_data = data;
}
public double Average
{
get
{
if (_average == null)
{
_average = _data.Average();
}
return _average.Value;
}
}
}
Here, the average is computed only once and then cached for subsequent access.
You can also embed validation logic in computed properties, especially useful when returning status indicators or derived metrics.
public class FormInput
{
public string Email { get; set; }
public bool IsEmailValid
{
get { return Email != null && Email.Contains("@"); }
}
}
This approach makes it easy to evaluate data validity as part of the property model.
Computed properties are also supported in struct types, enhancing their utility in value types.
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
public double DistanceFromOrigin
{
get { return Math.Sqrt(X * X + Y * Y); }
}
}
Here, DistanceFromOrigin is a computed property that calculates the Euclidean distance.
| Aspect | Computed Property | Method |
|---|---|---|
| Usage | Access like a variable | Invoke like a function |
| Best For | Simple, fast, repeatable calculations | Complex logic or operations with side effects |
| Performance | Inline, potentially better performance | May include more processing overhead |
| Clarity | Cleaner syntax for data-like behavior | Explicit intention for actions |
public class Invoice
{
public List- Items { get; set; }
public double TotalAmount
{
get { return Items.Sum(i => i.Price * i.Quantity); }
}
}
public class Item
{
public string Name { get; set; }
public double Price { get; set; }
public int Quantity { get; set; }
}
This practical example shows how computed properties can simplify business logic and increase clarity.
Computed properties are a powerful feature of C# that enhances encapsulation, improves code readability, and reduces redundancy. By calculating values on-the-fly based on other properties or fields, they keep the data model consistent and clean. Used effectively, computed properties make code more intuitive and maintainable. Whether you are building models, views, or data processing components, understanding and leveraging computed properties will help you write better C# applications.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved