C# Classes and Objects
Object-oriented programming with classes in C#
Class Definition
public class Person { # define class
public string Name; # public field
public int Age; # public field
public void Greet() { # public method
Console.WriteLine($"Hello, {Name}");
}
}
Constructor
public class Car {
public string Brand;
public Car(string brand) { # constructor
Brand = brand; # initialize field
}
}
Properties
public class Product {
private string _name; # private field
public string Name { # property
get { return _name; } # getter
set { _name = value; } # setter
}
public int Price { get; set; } # auto-property
}
Creating Objects
Person p = new Person(); # create object
p.Name = "John"; # set property
p.Age = 30;
p.Greet(); # call method
Car c = new Car("Toyota"); # with constructor
Inheritance
public class Animal { # base class
public void Eat() { }
}
public class Dog : Animal { # derived class
public void Bark() { }
}