Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Object-Oriented Programming in C# .NET - Part 1

0.00/5 (No votes)
3 Jul 2011 1  
An article that discusses Object-Oriented Programming in C# .NET

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:

byte[] dataArray = new byte[100000];
for(int i = 0; i < dataArray.Length; i++)
     {
         fileStream.WriteByte(dataArray[i]);
     }

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):

namespace OOPLearning
{
    class Program
    {
        static void Main(string[] args)
        {
            Car myCar = new Car ();
        }
    }
}

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:

namespace OOPLearning
{
    class Car
    {
        public int numberOfDoors;

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

Now, you can instantiate the Car class and access numberOfDoors and Accelerate:

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car ();
        myCar.numberOfDoors=4;
        Console.WriteLine (myCar.numberOfDoors);
        myCar.Accelerate ();
    }
}

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:

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car ();
        myCar.numberOfDoors=250;
        Console.WriteLine (myCar.numberOfDoors);
    }
}

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:

private int numberOfDoors;

public int NumberOfDoors
{
    get { return numberOfDoors; }
    set
    {
        if ( value >= 2 && value <= 6 )
        {
            numberOfDoors = value;
        }
    }

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:

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car ();
        myCar.NumberOfDoors=250;
        Console.WriteLine (myCar.NumberOfDoors);
        Console.ReadKey ();
    }
}

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:

private int numberOfDoors;

get { return numberOfDoors; }
set
{
    if ( value >= 2 && value <= 6 )
    {
        numberOfDoors = value;
    }
    else
    {
        numberOfDoors = 2;
    }
}

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.

Till then, have a good time coding.

History

  • 1st July, 2011: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here