C# is Object-Oriented Programming language and to achieve this we have make classes which are accessed by creating their respective objects.
Class
Class is a user defined prototype which can encapsulate different fields and methods or member functions into a single unit.
Creating a class consist of several keywords such as ,
1. Modifier
1. Modifier
2. Class keyword
3. Class name
Example of Class,
3. Class name
Example of Class,
// Creating a class of name Example with public modifier.
public class Example{
// A field of class.
public int val;
// Method of class.
public void hello(){
Console.WriteLine("Hello world.")
}
}
Objects
Objects are like variables of class type. They are used to access the fields or the methods of the class.
Initialization of object
Objects are initialized with new operator to instantiate a class by allocating it memory for object and reference to that memory. The new operator also invokes the constructor of the class.
public class Fruits{
public int no;
public string name;
public Fruits(int n, string na){
no = n;
name = na;
}
public void display(){
Console.WriteLine("Fruits number is "+no+" Fruits names are ",name);
}
}
public class Program{
public void main(string[] args){
// Here object f is initialized with new operator.
Fruits f = new Fruits(2, "Apples and Banana.");
f.display();
}
}