You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
C# is fundamentally an object-oriented language. Classes are blueprints for creating objects, and they encapsulate data (fields/properties) and behaviour (methods).
public class Person
{
// Fields (private by convention)
private string _name;
private int _age;
// Constructor
public Person(string name, int age)
{
_name = name;
_age = age;
}
// Method
public string Introduce()
{
return $"Hi, I'm {_name} and I'm {_age} years old.";
}
}
// Creating an object
var person = new Person("Alice", 30);
Console.WriteLine(person.Introduce());
Properties provide controlled access to fields:
public class Product
{
// Auto-implemented property
public string Name { get; set; }
// Property with a backing field
private decimal _price;
public decimal Price
{
get => _price;
set
{
if (value < 0) throw new ArgumentException("Price cannot be negative");
_price = value;
}
}
// Read-only property
public string Display => $"{Name}: £{Price:F2}";
// Init-only property (C# 9+)
public string Sku { get; init; }
}
var product = new Product { Name = "Widget", Price = 9.99m, Sku = "W001" };
// product.Sku = "W002"; // Error! init-only property
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.