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 modifiers
to 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 modifiers
explicitly then the class will by defaultinternal
as access modifier.
The classes are declared using the
class
keyword.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 :
namespace
is a way of organizing the code andnamespace
also helps in avoiding the naming collision of the class.The
access modifiers
for the above class isinternal
because we didn't mention it explicitly.The class
Add
has variables likea
,b
, andsum
. TheAdd
class also has a method namedSum
which takes above both values froma
andb
using the operator+
performs the addition operation and store the value returned value inside thesum
variable.
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
class
we use thenew
keyword.
Note: The objects created using the
new
keyword are stored inside theheap area
.
- Whenever we create the object of the class the constructor of that class gets called.
Note: Each and every
class
has 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.