Introduction to class and object in C#
Whenever we are dealing with the OOPS concepts we are generally using the class and object.
What is class?
The class and objects are the blueprint or prototype. The class can be created for the entity which has states and behaviors. The entity may be a living or non-living thing.
Declaring the class :
AccessModifiers class ClassName
{
// fields also known as variables
// functions also known as methods
}
- The class will always have
access modifiersto control the visibility of the class. To learn more about the access modifiers please check my blog on access modifiers.
Note: If we are not writing the
access modifiersexplicitly then the class will by defaultinternalas access modifier.
The classes are declared using the
classkeyword.The class will have the name and body the body of the class is surrounded using the
{ }.
Example :
namespace Demo
{
class Add
{
int a = 10;
int b = 20;
public int sum;
public void Sum()
{
sum = a + b;
}
}
class Program
{
public static void Main()
{
Add add = new Add();
add.Sum();
Console.WriteLine($"The sum of a and b : {add.sum}");
}
}
}
/*
Output :
The sum of a and b: 30
*/
Explanation :
namespaceis a way of organizing the code andnamespacealso helps in avoiding the naming collision of the class.The
access modifiersfor the above class isinternalbecause we didn't mention it explicitly.The class
Addhas variables likea,b, andsum. TheAddclass also has a method namedSumwhich takes above both values fromaandbusing the operator+performs the addition operation and store the value returned value inside thesumvariable.
Note: In
C#the execution of the program fromMain()only.
To access the variables and methods of the different classes we need to create the object of that class.
To create the object of the
classwe use thenewkeyword.
Note: The objects created using the
newkeyword are stored inside theheap area.
- Whenever we create the object of the class the constructor of that class gets called.
Note: Each and every
classhas will have a constructor of its own even if we didn't write the constructor explicitly. To learn more about Constructor please check my blog on constructor.
- By using the object reference we can call the methods and variable and perform the required operation.
