Click here to Skip to main content
Click here to Skip to main content

Tagged as

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

, 3 Jul 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Morteza Giti
Student
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
I live in Shiraz,Iran-the kingdom of Cyrus, The Great. I'm a university student and I'm studying software engineering at the moment. I began programming when I was around fifteen. 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. These days, I'm learning WPF and Silverlight. I also like MVC.

Comments and Discussions

 
GeneralThanks PinmemberNIRAJ KUMAR28-Mar-14 23:49 
QuestionUnity3D & C# Tutorial Videos PinmemberSamuel Asher Rivello4-Sep-13 7:00 
GeneralMy vote of 5 PinmemberSudhakar Shinde1-May-13 6:26 
GeneralMy vote of 5 Pinmemberm0hammad.sh29-Apr-13 5:09 
GeneralMy vote of 5 Pinmembercodertuhin10-Jan-13 0:13 
GeneralMy vote of 5 Pinmemberacharya paresh7-Dec-12 4:18 
QuestionEverything in C# .NET is NOT a class , PinmemberSia_Mak29-Nov-12 8:20 
GeneralMy vote of 5 PinmemberJD-Gabriiel15-Oct-12 13:24 
QuestionGood and Concise PinmemberSimeon Abiodun10-Jul-12 6:10 
GeneralMy vote of 5 PinmemberMalik ZeeV9-Apr-12 22:43 
Simply, Great Story Telling.
GeneralRe: My vote of 5 Pinmembermoaazmohali28-Jan-13 11:00 
GeneralMy vote of 3 PinmemberKuhyar19-Feb-12 0:08 
SuggestionThis is a good and concise introduction and I'm enjoying reading it PinmemberTaipeiJim11-Jul-11 16:58 
Questionnot bad PinmemberCIDev8-Jul-11 4:04 
GeneralMy vote of 4 Pinmembergrosende16-Jul-11 20:28 
QuestionMissing main concepts Pinmemberrwt334-Jul-11 11:30 
AnswerRe: Missing main concepts PinmemberMortezaCoder5-Jul-11 21:20 
GeneralMy vote of 3 PinmemberHamlet Escaño4-Jul-11 5:08 
GeneralRe: My vote of 3 PinmemberMortezaCoder5-Jul-11 21:18 
GeneralAlready exist. Pinmemberalvil1990@yahoo.com3-Jul-11 23:50 
GeneralRe: Already exist. PinmemberMortezaCoder5-Jul-11 21:22 
GeneralRe: Already exist. PinmemberFabio Franco7-Jul-11 4:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411022.1 | Last Updated 3 Jul 2011
Article Copyright 2011 by Morteza Giti
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid