Introduction To Classes And Objects In Object-Oriented Programming In C#
Tags: csharp, beginners, coding
Published: 2020-06-04 09:45:20


This topic was one that I struggled with when I started coding in c#. I created this post to help explain this concept to other people who might be struggling with this. Often times after getting comfortable with variables, data structures and conditional statements, the next line of action would be understanding classes, objects and object-oriented programming. In this article, I hope to breakdown this Goliath.

##Why Classes and  Objects?

Object-Oriented Programming is based on the concept of objects and classes. A class is used to bind data as well as methods together as a single unit. An object is the instance of the class, which helps programmers to use variables and methods of the class. 

Classes are important because often times during development we are going to be dealing with collections. Whether we realize it or not everything around us is a class (a collection of attributes and functionalities), even water is a combination of Hydrogen and Oxygen. So a class is basically a collection of characteristics and properties that define an entity.

Let us create a class Person with attributes Name, Age, Gender, Occupation and functionalities Walk(), Eat(), Sleep().
###Example:
class Person 
{ 
Name,
Age,
Gender,
Occupation, 
Walk(),
Eat(),
Sleep()
}

 ![Class Person](https://dev-to-uploads.s3.amazonaws.com/i/69esbt14hjr4yca0a1g2.png)
<figcaption>Class Person</figcaption>

Just like that you have created a class and you have given it properties and methods.

Next you might be wondering so how can I apply it to a programming scenario. To explain this I will use your favorite social media app's registration page for example.

  ![FaceBook SignUp Page](https://dev-to-uploads.s3.amazonaws.com/i/eswbunnkljp1k80f3aib.jpg)
<figcaption>FaceBook SignUp Page</figcaption>
This page contains:

Firstname
Surname
EmailAddress
Password
BirthDay

We could pass these properties to our API to store them on the database as individual variables but a smarter and more efficient way is to group them into a single class and assign it a name.

###Example:

```csharp
 public class Register
 {
    ///A class is created using the (**class** keyword)
    ///The public keyword is an access modifier and means that the 
    ///class is public and accessible everywhere within this context.
    public string Firstname { get; set; }

    public string Surname { get; set; }

    public string EmailAddress { get; set; }

    public string Password { get; set; }

    public DateTime BirthDay { get; set; } 

   ///The purpose of the { get; set; } is to retrieve a value(get) and 
   ///assign a value(set) to a property.
}
```
<figcaption>Register Class</figcaption>

###Note:
_FirstName, Surname, EmailAddress, Password are public properties of class **Register** and are of type string. BirthDay is also a property but of type DateTime. Type string means it can only accept a string variable. You can define what type you want your property to accept_

So now that we are done with the basic explanation of classes let's dive deeper.

if we take a look at the SignUp Page we will see that users will typically enter their Birthday in the format (yyyy/mm/dd) we then want to calculate the user's real age today from his date of birth for that we create a method GetUsersCurrentAge()in the Register class it would then look like this.

```csharp
 public class Register
 {
    public string Firstname { get; set; }

    public string Surname { get; set; }

    public string EmailAddress { get; set; }

    public string Password { get; set; }

    public DateTime BirthDay { get; set; }
       
    public int GetUsersCurrentAge(){/*logic to get age*/}
              
 }
```
<figcaption>GetUsersCurrentAge Method added to the Register Class</figcaption>

Now the Register class contains both properties and also a method GetUsersCurrentAge(). Classes can also contain other Classes.
Let's say in the app you have the messages class and it contains these properties.

```csharp
public class Messages
{
   public string Sender { get; set; }

   public string Recipient { get; set; }
        
   public string MessageContent { get; set; }

}
```
<figcaption>Messages Class</figcaption>
you can then combine the Messages Class to the Register Class.
```csharp
public class Register
{
   public string Firstname { get; set; }

    public string Surname { get; set; }

    public string EmailAddress { get; set; }

    public string Password { get; set; }

    public DateTime BirthDay { get; set; }
          
    public int GetUsersCurrentAge(){//logic to get age}

    public Messages messages { get; set; }
      //Messages Class has been added to the RegisterClass
      //with all it's properties
}
  
public class Messages
{
   public string Sender { get; set; }

   public string Recipient { get; set; }
        
   public string MessageContent { get; set; }
 }

```
<figcaption> Messages Class binded to the Register Class</figcaption>

##How to Access a Class

Let's say in another component of  your social media application like the (Notifications) you wanted to also know when a user followed someone or liked someone's picture. For example I liked Grace's picture today 2020/31/05 in a couple of days time we want to show Grace how many days ago I liked her picture, now you might say let's just create a new method for that but if you recall we had done a similar method in the[Register class] so I can reuse that method instead of creating a new one I just need to be able to access that class and it's methods.

We can do this by instantiating  the class, an instance of the class is called an **OBJECT**. It is like a replica of that class that helps us access all the properties and methods of that Class.

How do we do this
```csharp
var registerObject=new Register();
```
This means that all the properties and methods of Register class are now in **registerObject**.

So I can access the GetUsersCurrentAge() method by doing this
```csharp
registerObject.GetUsersCurrentAge();
```
I can also access the other properties of the Register class in a similar manner:
```csharp
registerObject.Firstname;
registerObject.SurName;
```
The basic principle of an object is that it must contain a key and a value. In the **registerObject** the keys are the properties which are FullName, UserName, EmailAddress, Password and BirthDay and we can assign values to them like this:
```csharp
registerObject.Firstname="John";
registerObject.SurName="Doe";
registerObject.EmailAddress="p@gmail.com";
registerObject.Password="p@ssword";
registerObject.Birthday="1973/09/20";
```
and supposing we wanted to retrieve the Firstname from this object we would do this;
```csharp 
string firstName= registerObject.FirstName;
```
To access the **Messages** class we would first instantiate it.
```csharp
registerObject.messages= new Messages();
```
then assign values like this
```csharp
registerObject.messages.Sender="Gbenga James";
```
###Note:New Keyword
```csharp
var registerObject=new Register();
```
_The purpose of the new keyword is to access an instance of the class which means that any change you make to the values affects just the instance of it._

So in this instance of class Register these are the values.
```csharp
registerObject.FullName="John Doe";
registerObject.UserName="JDee";
registerObject.EmailAddress="p@gmail.com";
registerObject.Password="p@ssw0rd";
registerObject.DateOfBirth="1973/09/20";
```

I could create another instance and assign totally different values .
```csharp
var registerObject2=new Register();
```
and we can assign values like this
```csharp
registerObject2.FullName="Gbenga Daniels";
registerObject2.UserName="GDee";
registerObject2.Password="password";
registerObject2.DateOfBirth="1988/07/16";
```

We could then use this object in our application, so basically we are reusing a class and its methods by creating instances(Objects) of it, this is the beauty of object-oriented programming being able to do more work with less code, reuse properties and methods in different parts of the application and improve code performance and efficiency.
We have come to the end of this article and I hope you understand the basic concepts of Classes and Objects in Object-Oriented Programming.

###To reiterate:
1. Classes are a collection of methods and properties of an entity they help with code reusability and performance.

2. Properties of classes can be accessed by creating instances of the classes called OBJECTS.

I will end the article here so it does not become overwhelming, but this is the basic principle of classes and objects and an introduction into object-oriented programming in my next article we would be exploring the 4 tenets of Object-Oriented programming. Check it out here [Principles of Object Oriented Programming](https://dev.to/gbengelebs/principles-of-object-oriented-programming-part-1-inheritance-308e)

Follow me here and across my social media for more content like this [Twitter](https://twitter.com/ElegberunDaniel?s=09) [Linkedin](https://www.linkedin.com/in/olugbenga-elegberun/)