Click here to Skip to main content
15,860,859 members
Articles / Programming Languages / C#

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

Rate me:
Please Sign up or sign in to vote.
4.76/5 (49 votes)
3 Jul 2011CPOL6 min read 178.3K   65   24
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.

C#
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:

C#
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:

C#
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:

C#
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:

C#
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:

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

C#
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:

C#
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:

C#
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:

C#
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:

C#
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:

C#
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:

C#
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:

C#
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)


Written By
Software Developer (Senior)
Iran (Islamic Republic of) Iran (Islamic Republic of)
I'm a software engineer specialized in .NET framework. I've developed applications in such technologies as Console Applications, Windows Forms, WPF, Web Forms, MVC, Silverlight and Xamarin Forms. I also create and publish my multimedia courses at provid.ir and softdevwithmorteza.wordpress.com.
Some of my courses inclue Design Patterns in C#, OOP Principles, SOLID Principles, High Quality Coding Principles, Anti-patterns, Refactoring, TDD, DDD, .NET Core and so on.

Comments and Discussions

 
GeneralMy vote of 3 Pin
Member 121020743-Nov-15 23:11
Member 121020743-Nov-15 23:11 
Questionhi friends Pin
Member 1126259525-Nov-14 2:00
Member 1126259525-Nov-14 2:00 
GeneralThanks Pin
NIRAJ KUMAR28-Mar-14 22:49
NIRAJ KUMAR28-Mar-14 22:49 
QuestionUnity3D & C# Tutorial Videos Pin
Samuel Asher Rivello4-Sep-13 6:00
Samuel Asher Rivello4-Sep-13 6:00 
GeneralMy vote of 5 Pin
Sudhakar Shinde1-May-13 5:26
Sudhakar Shinde1-May-13 5:26 
GeneralMy vote of 5 Pin
Mohammad Sharify29-Apr-13 4:09
Mohammad Sharify29-Apr-13 4:09 
GeneralMy vote of 5 Pin
codertuhin9-Jan-13 23:13
codertuhin9-Jan-13 23:13 
GeneralMy vote of 5 Pin
acharya paresh7-Dec-12 3:18
acharya paresh7-Dec-12 3:18 
QuestionEverything in C# .NET is NOT a class , Pin
Sia_Mak29-Nov-12 7:20
Sia_Mak29-Nov-12 7:20 
GeneralMy vote of 5 Pin
JD-Gabriiel15-Oct-12 12:24
JD-Gabriiel15-Oct-12 12:24 
QuestionGood and Concise Pin
Simeon Abiodun10-Jul-12 5:10
Simeon Abiodun10-Jul-12 5:10 
GeneralMy vote of 5 Pin
Malik ZeeV9-Apr-12 21:43
Malik ZeeV9-Apr-12 21:43 
GeneralRe: My vote of 5 Pin
moaazmohali28-Jan-13 10:00
moaazmohali28-Jan-13 10:00 
GeneralMy vote of 3 Pin
Kuhyar18-Feb-12 23:08
Kuhyar18-Feb-12 23:08 
SuggestionThis is a good and concise introduction and I'm enjoying reading it Pin
TaipeiJim11-Jul-11 15:58
TaipeiJim11-Jul-11 15:58 
Questionnot bad Pin
BillW338-Jul-11 3:04
professionalBillW338-Jul-11 3:04 
GeneralMy vote of 4 Pin
simbacat9116-Jul-11 19:28
simbacat9116-Jul-11 19:28 
I see it as a good start for beginer and a refresher for a c#programmer just wanting to refresh from not doing it for a while.
QuestionMissing main concepts Pin
rwt334-Jul-11 10:30
rwt334-Jul-11 10:30 
AnswerRe: Missing main concepts Pin
Morteza Giti5-Jul-11 20:20
Morteza Giti5-Jul-11 20:20 
GeneralMy vote of 3 Pin
Hanlet Escaño4-Jul-11 4:08
Hanlet Escaño4-Jul-11 4:08 
GeneralRe: My vote of 3 Pin
Morteza Giti5-Jul-11 20:18
Morteza Giti5-Jul-11 20:18 
GeneralAlready exist. Pin
alvil1990@yahoo.com3-Jul-11 22:50
alvil1990@yahoo.com3-Jul-11 22:50 
GeneralRe: Already exist. Pin
Morteza Giti5-Jul-11 20:22
Morteza Giti5-Jul-11 20:22 
GeneralRe: Already exist. Pin
Fabio Franco7-Jul-11 3:40
professionalFabio Franco7-Jul-11 3:40 

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

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