DEV Community

Cover image for Introduction To Classes And Objects In Object-Oriented Programming In C#
Elegberun Olugbenga
Elegberun Olugbenga

Posted on • Edited on

Introduction To Classes And Objects In Object-Oriented Programming In C#

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

Class Person

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

FaceBook SignUp Page

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:



 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.
}


Enter fullscreen mode Exit fullscreen mode
Register Class

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.



 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*/}

 }


Enter fullscreen mode Exit fullscreen mode
GetUsersCurrentAge Method added to the Register Class

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.



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

   public string Recipient { get; set; }

   public string MessageContent { get; set; }

}


Enter fullscreen mode Exit fullscreen mode
Messages Class

you can then combine the Messages Class to the Register Class.



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; }
 }



Enter fullscreen mode Exit fullscreen mode
Messages Class binded to the Register Class

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



var registerObject=new Register();


Enter fullscreen mode Exit fullscreen mode

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



registerObject.GetUsersCurrentAge();


Enter fullscreen mode Exit fullscreen mode

I can also access the other properties of the Register class in a similar manner:



registerObject.Firstname;
registerObject.SurName;


Enter fullscreen mode Exit fullscreen mode

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:



registerObject.Firstname="John";
registerObject.SurName="Doe";
registerObject.EmailAddress="p@gmail.com";
registerObject.Password="p@ssword";
registerObject.Birthday="1973/09/20";


Enter fullscreen mode Exit fullscreen mode

and supposing we wanted to retrieve the Firstname from this object we would do this;



string firstName= registerObject.FirstName;


Enter fullscreen mode Exit fullscreen mode

To access the Messages class we would first instantiate it.



registerObject.messages= new Messages();


Enter fullscreen mode Exit fullscreen mode

then assign values like this



registerObject.messages.Sender="Gbenga James";


Enter fullscreen mode Exit fullscreen mode

Note:New Keyword



var registerObject=new Register();


Enter fullscreen mode Exit fullscreen mode

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.



registerObject.FullName="John Doe";
registerObject.UserName="JDee";
registerObject.EmailAddress="p@gmail.com";
registerObject.Password="p@ssw0rd";
registerObject.DateOfBirth="1973/09/20";


Enter fullscreen mode Exit fullscreen mode

I could create another instance and assign totally different values .



var registerObject2=new Register();


Enter fullscreen mode Exit fullscreen mode

and we can assign values like this



registerObject2.FullName="Gbenga Daniels";
registerObject2.UserName="GDee";
registerObject2.Password="password";
registerObject2.DateOfBirth="1988/07/16";


Enter fullscreen mode Exit fullscreen mode

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

Follow me here and across my social media for more content like this Twitter Linkedin

Top comments (2)

Collapse
 
bendiagi profile image
Ebenezer Diagi

Very informative and well written.

Collapse
 
ekirigwe profile image
Samuel Ekirigwe

Very well done Sir. This is such a vital topic and this article is very much welcome