Classes

Classes also known as types are like building blocks of our application. Classes combine related variables, functions (methods) and events together. A Class is like a blueprint. It describes data and behavior of an object. So how to declare a class? Here is three main components – access modifier, class keyword, and identifier.

Copy
1public class Animal
2{
3 //Prop's goes here
4}

In this code, is declared a publicly accessible class called Animal. The class can be given private, protected, static and no access modifier – depends on our need. When the class has been declared, we can add properties to that and describe it’s behavior. So let’s say, the class will have field’s Name, Age, and Weight and methods Walk(), Eat(), and Sleep().

Copy
1public class Animal
2{
3 public string Name;
4 public int Age;
5 public int Weight;
6
7 public void Walk()
8 {
9 //Some code here
10 }
11
12 public void Eat()
13 {
14 //Some code here
15 }
16
17 public void Sleep()
18 {
19 //Some code here
20 }
21}

So now we see, that this class is like a blueprint for our object. They are not same – class describes a type of object. To create the object we need to make new variable and initialize it, this can be done with the following line.

Copy
1Animal Fox = new Animal();

To make this code shorter, object initialization can be written like so:

Copy
1var Fox = new Animal();

To access the object properties and methods dot notation can be used.

Copy
1Fox.Name = "Foxy";

For better demonstration, I’m going to create a new class called PlayWithAnimal and inside this class, I’m going to create a method to give fox name.

Copy
1public class PlayWithAnimal
2{
3 private void GiveFoxName()
4 {
5 Animal Fox = new Animal();
6
7 Fox.Name = "Foxy";
8 }
9
10}

In this code publicly accessible class has been created and it is called PlayWithAnimal. Inside this class is private method GiveFoxName, and inside a method is initialized Fox object and for the property, Name is given new value – “Foxy”. In this post, I described how to declare a class with some properties and methods, how to initialize an object and access object parameter with dot notation. In next post, I’m going to take a closer look for access modifiers, play with them and give some code examples.

Remember that object is an instance of a class. And process of creating the object is called object initialization.