Class
Classes serve as the building blocks of software applications. A class encapsulates data (stored in fields) and behavior (defined by methods). In other words, the anatomy of the class is comprised of Data (represented by fields) and Behaviour(represented by methods/functions).
Example. How to declare class?
public class Customer
{
// Field
public string Name;
// Method
public void Promote()
{
// Method implementation
}
}
Object
An object represents a specific instance of a class. It is instantiated using the new operator.
Customer customer = new Customer();
// Or
var customer = new Customer();
Constructors
A constructor is a function invoked during the instantiation of a class. Constructors are utilized to initialize an object's initial state. It's advisable to define a constructor solely when an object necessitates initialization for it to function properly. Constructors that lack a return type, including void, should bear identical names to their respective classes.
Constructors can be overloaded, which means we can create methods with the same name but different types or numbers of parameters. The signature of a method includes the types and order of its parameters. We can use this keyword to switch control from one constructor to another.
public class Client
{
// Properties
public int ID;
public string FullName;
public List<Order> Purchases;
// Default constructor
public Client()
{
// Prepare the list for purchases
Purchases = new List<Order>();
}
// Constructor with an ID parameter
public Client(int id) : this()
{
// Set the client's ID
this.ID = id;
}
}
Methods
A method's signature includes details like how many parameters it has, what types they are, and the order they appear in. When we overload a method, we create multiple methods with the same name but different parameter setups. This helps users choose the right method for the data they want to give.
public class Point {
// Moves the point to a new position specified by x and y coordinates
public void Move(int x, int y) {}
// Moves the point to a new location specified by another Point object
// This is an overloaded version of the Move method
public void Move(Point newLocation) {}
}
We can use the 'params' keyword to let a method take different amounts of parameters.
public class Calculator {
// The Add method can receive a variable number of integer parameters
// thanks to the 'params' modifier
public int Add(params int[] numbers) {}
}
Fields
A field can be set up in two ways: during construction or right when it's declared. By initializing a field upon declaration, you ensure it's always set, regardless of which constructor is used.
// This Customer class automatically initializes the Orders list when declared.
public class Customer {
public List<Order> Orders = new List<Order>();
}

Join the conversation! Your thoughts help the community grow.