Creating a class in C# -Learn what is class and how to write a class in C# with simple example and explanation.
A class is a template that contains properties(variables) and behaviors(methods). We can create many objects of it.
Sounds difficult? Read till end and you understand class in C# for sure! It’s Simple!!!
For example, a person has some properties and behaviors. As a property, a person has his name, age, gender etc. and behavior as eat and sleep etc.
So, we can convert a person class as below in C#. Simply convert all properties as variables/ class fields and behaviors/ operations into a method. That’s simple.
Example of creating a class in C#
class Person
{
// properties
String name;
int age;
// Behaviors
public void eat()
{
// write about behaviors
}
public void sleep()
{
//// write about behaviors
}
}
A template for person class we have created. Now, we can create many objects of the person class. Objects can be any person i.e. Peter, John and Linda etc.
Everyone has his properties and behaviors i.e. name and age etc and behaviors eat and sleep etc.
Similarly, everything you see around you are objects like Car, book, pen and computer etc. for that you can create a template /blue print and create objects of them.
See one more example, a Car his properties like model and brand etc and behavior run. So, we can convert into a class as below. Convert model into a property and behavior int a method.
class Car {
String model;
void run()
{
//defintion
}
}
Exercise:
Create a class Dog, that has 3 properties (class fields) breed, age and colour with behaviours (class method) bark and sleep.
Solution:
class Dog {
// Properties
String breed;
int age;
String colour;
// Behaviors
public void bark() {
}
public void sleep() {
}
}