Lesson 12 of 15
Properties
Properties
Properties are the idiomatic C# way to expose data with optional validation:
class Person {
private int _age;
public string Name { get; set; } // auto-property
public int Age {
get => _age;
set {
if (value < 0) throw new ArgumentException("Age cannot be negative");
_age = value;
}
}
public Person(string name, int age) {
Name = name;
Age = age;
}
}
Computed Properties
A property with only a get computes its value on the fly:
class Circle {
public double Radius { get; set; }
public double Area => Math.PI * Radius * Radius; // computed
public double Diameter => 2 * Radius; // computed
}
Init-Only Properties (C# 9+)
class Point {
public int X { get; init; } // set only in constructor or init
public int Y { get; init; }
}
var p = new Point { X = 3, Y = 4 };
Your Task
Create a Temperature class with:
double Celsius { get; set; }property- A computed
double Fahrenheitproperty that returnsCelsius * 9.0 / 5.0 + 32 - A constructor taking a
celsiusvalue
WasmSharp (.NET) loading...
Loading...
Click "Run" to execute your code.