public class Person
{
// Fields
private string _name;
private int _age;
// Properties
public string Name
{
get => _name;
set => _name = value;
}
public int Age
{
get => _age;
set
{
if (value >= 0)
_age = value;
}
}
// Auto-property
public string Email { get; set; }
// Constructor
public Person(string name, int age)
{
_name = name;
_age = age;
}
// Method
public void Introduce()
{
Console.WriteLine($"Hi, I'm {_name}, {_age} years old.");
}
}
// Sử dụng
var person = new Person("Alice", 30);
person.Introduce();
public class Animal
{
public string Name { get; set; }
public virtual void MakeSound()
{
Console.WriteLine("Some sound");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof!");
}
public void Fetch()
{
Console.WriteLine("Fetching ball...");
}
}
// Sử dụng
Animal myDog = new Dog();
myDog.MakeSound(); // "Woof!"
public abstract class Shape
{
public abstract double CalculateArea();
}
public class Circle : Shape
{
public double Radius { get; set; }
public override double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override double CalculateArea()
{
return Width * Height;
}
}
// Sử dụng đa hình
List<Shape> shapes = new List<Shape>
{
new Circle { Radius = 5 },
new Rectangle { Width = 4, Height = 6 }
};
foreach (var shape in shapes)
{
Console.WriteLine($"Area: {shape.CalculateArea()}");
}