Introduction

In this article, I want to show you the concept of Object-Oriented Programming in C#. Now what are objects and why we’d better write Object-Oriented applications? Good Question! We will cover the following:

What is an object?

Creating a class

Fields

Methods

Instantiating your class

Access Modifiers

Properties

What is an Object

In order to understand the meaning of object in our context, you should first understand the concept of classes. Everything in C# .NET is a class. From integer data type to complex encryption and ADO.NET classes. So, for example, when you write the following code, you are actually using FileStream class to declare a variable name fileStream.

FileStream fileStream = new FileStream(fileName, FileMode.Create));

So, as you can see, fileStream is a variable of type FileStream which is a class. We call fileStream an object or an instance of type FileStream class rather than a variable because everything is considered as an object. I hope I have made myself clear so far. So, keep in mind that every instance of a class is called an object.

So far we have seen what the difference between a class and an object is. The following is Microsoft’s definition of these terms:

A class definition is like a blueprint that specifies what the type can do. An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances.

Every instance of a particular class can access some properties and methods of that class. For example, considering fileStream as an object of type FileStream class, we could write:

fileStream is calling WriteByte which is a method declared in FileStream class and what it does is not of any interest to us right now. We can also access the properties that are allowed via our instance of a class. Again, assuming fileStream to be an instance of FileStream class, we could write:

if (fileStream.CanWrite)
{
Console.WriteLine("The stream for file is writable.")
}
else
{
Console.WriteLine("The stream for file is not writable.");
}

I think you have got the idea of classes and objects. However, this was the beginning. I don’t want to go through the classes provided by Microsoft and guide you how to use them but rather I want to show you how you can declare classes of your own. The classes that you create can have methods and properties similarly to those already in the .NET and you can set access policies to those methods and properties which we call members from now on.

Creating a Class

To create a class, you need to add a class file to your project. Right-click on your project inside the solution explorer and click Add and then choose New Item…. On the left side of the new window, navigate to Code template and then click Class from the right-sided pane. Choose a name for your class and click Add. A new file is added to your project. Inside it, you see the declaration of your class as follows. I have named my class Car and it is in the OOPLearning namespace:

namespace OOPLearning
{
class Car
{
}
}

Fields

To add a field (and a field is simply an object within your class, it could by an integer or any other object) just write the data type of the field and the name:

int numberOfDoors;

In the above line of code, I have declared a field of type int which stores the number of the doors that an instance of this class has.

Methods

Methods are the behaviors of your class; the things that an object of that class can do. For example, a class named Dog may have a method named Bark, as dogs bark. And a class named Car can have a method named Accelerate, as cars can accelerate.

We add a method to our class in this manner:

void Accelerate()
{
//The logic goes here
}

I have eliminated the logic for this method because it’s not of any interest to us right now.

Instantiating your Class

Instantiating (creating an instance of a class) is simply the process of declaring an object of a class. You can instantiate a class as follows (I have created a console application and declared an object of type Car in the Main method of the Program.cs file of my project):

Access Modifiers

As I said, when you create an instance of a class, you can access the members (methods and fields) of that class via your instance. So, this means that I could write the following:

Car myCar = new Car ();
myCar.numberOfDoors=4;
myCar.Accelerate ();

But as you see, the above code has generated an error. Why is that? Because we don’t have access to these members and this is due to their access modifiers which are private. The private keyword is not explicitly written before the Accelerate and numberOfDoors. But since it’s the default access modifier, anything (either method, fields, etc.) that you declare in your class is considered private unless you write one of the following before them:

public

protected

internal

internal protected

We don’t go through these keywords right now. Let’s just change the definition of our class as follows:

Notice that I have set numberOfDoors to the value 4 and then print it out on the console. Simple as that.

Properties

Remember I said fields act as stores for your data. The numberOfDoors is the storage in which we store the number of doors our myCar object has. What if we wanted to control the value passed to this field. For example, the following code would be perfectly valid:

But we know that there is no car in the whole world which has 250 doors. We want to make sure the value passed to numberOfDoors is intellectually acceptable. So, we use properties. A property is simply a method that which can help us add logic to when the value of a field is retrieved or set. Look at the following line of code:

As it’s obvious, we control the value passed to the numberOfDoors and only accept it if it’s between 2 and 6. Now, the property named NumberOfDoors is actually a method which has two parts: get, set. The get part is called whenever we retrieve the value stored in nubmerOfDoors and the set part is called whenever we pass a value to be stored in numberOfDoors. Notice the data type of the property and the field match. Also, pay attention to the syntax. Now, if we write the following code, we see the value 0 in the console as the default value of type integer is:

What happened is simply logical. Since the value passed to NumberOfDoors doesn’t conform to our rules (between 2 and 8) the default value of type integer which is zero (which is stored in the field numberOfDoors) is returned. To better understand the concept, let’s change our class to look like this:

Now run the project again. You see 2 in the console. And that’s because of the else in the set part of NumberOfDoors. If the value passed to the property conforms to our rule, then everything is quite good, otherwise it is set to value 2. There is a lot to properties, but we close our discussion on them here.

You can continue your Object-Oriented Programming in Part 2 of this article.

Share

About the Author

I have an Msc. in software engineering. Actually, I began programming when I was around eleven. Having started my journey with VB6, I moved to VB.NET after two years and one year later I turned my face to C# as I found it more interesting and challenging. Through the years, I have developed Console Apps, Windows Apps (both Windows Forms and WPF), Silverlight, ASP.NET (both Web Forms and MVC), Android Apps and a bunch of other stuff. These days, I'm studying Web API, Mono for Anroid and Web platforms such as AngularJS and KnockoutJS. I have a great passion for research and learning. I also design and publish online multimedia courses on my website at provid.ir.

Again, like many 'introduction to OOP' guides, you miss the main concepts that would drive people to need to start using an OOP approach as opposed to any other. I 'learnt' OOP long before I understood the concepts of why I should use OOP, and it was murder - and fruitless.
Of course everyone's take on it is likely to be different, but I'm sure many like me are or have been in that position.

I read the beginning of the article because I want to share it with a friend which is new to software development. It might be a start for new developers but then you start talking about data types, memory allocation and instance of objects and it does not seem that it is targeted to beginners anymore. I will still share it with my friend though Thanks.

Dear friend. It is, indeed, targeted for the beginners. However, it also provides some advanced tips in a very simple language so that the beginners can understand too. Anyway, I think if you study all the parts you will enjoy it more.

One of the beauties of the internet is the fact that it have several sources on the same subject. You can make the best of all you can find and can build a more reliable base when several sources say the same thing.

By the way, "alvil" already exists on the internet, does it keep you from using it? I guess that's why you have a number after it.