Click here to Skip to main content
15,880,905 members
Articles / Programming Languages / C#

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

Rate me:
Please Sign up or sign in to vote.
4.31/5 (13 votes)
7 Jul 2011CPOL6 min read 45K   30   9
In this part of the article, I will continue my discussion on OOP by discussing methods, properties and access modifiers.

Introduction

In this part of the article, I will continue my discussion on OOP (Object-Oriented Programming) even further. I highly recommend that you study the first part of this series if you haven’t already done so.

We will talk more about:

  • Methods
  • Properties
  • Access Modifiers

Methods

In the first part of this series, I briefly introduced methods. However, in this part, I will show you much more about methods. Remember methods are behaviors of your class. So, a method can return a result after doing that behavior or not return anything (return void). For example, the following method adds two digits and returns the result of the summation:

C#
public double Add()
{
    double x = 3;
    double y = 2;
    return x + y;
}

Methods can have parameters. A parameter is some value that is passed to the method when it’s called. Look again at the updated version of our Add method:

C#
public double Add(double x, double y)
{
    return x + y;
}

As you can see, this method accepts two parameters of type double and returns the value indicating their summation. Now, assuming this method is declared in a class named CustomMath, we can call it from our Main (the entry point of the program) like this:

C#
class Program
{
    static void Main(string[] args)
    {
        CustomMath cm = new CustomMath ();
        double result = cm.Add ( 3.1, 4.5 );
        Console.WriteLine (result );
        Console.ReadKey ();
    }
}

If you run the application, you will see the value 7.6 on the screen.

Now, methods can return nothing (return void). Look at the following method:

C#
public void Add(double x, double y)
{
    double z = x + y;
}

Although this method does some work, it doesn’t return anything. Now, methods that return void may or may not have parameters. And the same goes with methods that return a value; they may or may not have parameters.

The Params Keyword

Some methods can have one or more input parameters. I mean that when they are called, they let you specify as many parameters as you want. Take a look at the following method signature for understanding this better:

C#
public int AddMany(params int[] digits)
{
    int result = 0;
    foreach ( int item in digits  )
    {
        result += item;
    }
    return result;
}

This method is declared in CustomMath class. So, we could call it like this:

C#
class Program
{
    static void Main(string[] args)
    {
        CustomMath cm = new CustomMath ();
        int customResult = cm.AddMany ( 1, 3, 5, 6, 7, 3, 8, 4, 8, 2, 4, 2 );
        Console.WriteLine (customResult );
        Console.ReadKey ();
    }
}

And we get 53 as output on the console. Now, notice that in the signature of the AddMany method in CustomMath class, I didn’t specify the number of the input parameters. I used the params keyword to let the user add as many parameters as he/she needs. The following calls to AddMany are all correct and legal:

C#
int customResult = cm.AddMany ( 1, 3, 5, 6, 4, 8, 2, 4, 2 );
int customResult = cm.AddMany ( 1, 3, 5, 6, 5, 3, 4, 76, 11, 99, 4, 8, 2, 4, 2 );
int customResult = cm.AddMany 
		( 1, 3, 44, 3, 67, 5, 6, 5, 3, 4, 76, 11, 99, 4, 8, 2, 4, 2 );

The thing to bear in mind is that all the parameters must be of type integer as specified in the method signature.

Well, enough with methods. Let’s move our face to properties once again.

Properties

For an introduction to properties, refer to part one of this series.

You can omit either the set accessor or the get accessor, but not both. When the set accessor of a property is omitted, that property is treated as read-only. On the other hand, the get accessor is omitted, it’s considered to be write-only. Take a look at the following lines of code which are written in the Car class:

C#
private int readOnly;
 
public int ReadOnly
{
    get { return readOnly; }
}  

Now, you can only read the value stored in ReadOnly. Therefore, if you try the following line of code, you will be stopped with an error indicating that the property is read-only:

C#
class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car ();
        myCar.ReadOnly = 3;
        Console.ReadKey ();
    }
}

However, the following code will perfectly compile as you are reading the value stored in ReadOnly. You will see 0 on the screen if you run the project as it is the default value of type integer.

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

In the same manner, you can omit the get accessor and make the property write-only. Look at the following lines of code:

C#
private int writeOnly;
 
public int WriteOnly
{
    set { writeOnly=value ; }
} 

Since the WriteOnly only has the set accessor, you can just write values to it:

C#
class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car ();
        myCar.WriteOnly = 3;
        Console.ReadKey ();
    }
}

If you try to get the value stored in it, you will encounter an error:

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

Note that you cannot omit both the set and the get accessor of the property.

I think it’s enough with the properties. Let’s now go and learn more on access modifiers.

Access Modifiers

To see the introduction to access modifiers, refer to part one of this article.

Access modifiers can be applied to almost anything within a class; a method, a field, a property, even the individual set and get accessors of a property.

Now, let’s go into the details of each one in turn.

What does private access modifier do?

The private access modifier makes a member only available within the class it’s declared in. A member that is marked as private is not accessible out of the class. The classes that derive from the class containing the private member cannot access a private member either. (The concept of derivation and inheritance will be discussed later.) Suppose we have declared Name in our Car class as follows:

C#
class Car
{
    private string Name;
}

Outside the Car class (in our Main entry point, for example), we cannot access this member via an object of type Car. In other words, the following line of code causes an error:

C#
class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car ();
        myCar.Name = "SampleName";
    }
}

However, within the Car class itself, we can have access to Name without any problem as this member is declared in Car class and we are currently in Car class:

C#
class Car
{
    private string Name;
        
    public void PrintName()
    {
        Console.WriteLine (Name);
    }
}

I think you got the idea so far. Now, let’s turn our face to public access modifier.

What does public access modifier do?

The public modifier makes a member available to any code that has access to the class in which that member is declared. As in the previous code, the PrintName method is declared as public, so we code successfully compile and run the following code:

C#
class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car ();
        myCar.PrintName ();
    }
}

Since we have access to Car class in our Main method, we have access to all public members as well. Hope you got what I mean. Let’s get to know about protected modifiers.

What does protected access modifier do?

The protected modifier is similar to private modifier with a little difference. Remember when I introduced the private modifier; I said derived classes cannot access a private member of the base class either. In terms of protected modifier, the story differs. A protected member is only available within the class it’s declared in (so far like the private modifier) and the classes that derive from the class that member is declared in. (you will notice the difference when I talk about inheritance later on.) Now, let’s introduce the final access modifier and put an end to this part of the article.

What does internal access modifier do?

The internal modifier makes a member available only to the classes in the same assembly. Now, what is an assembly? I will not answer that question right now as it’s not a topic for this part of the article, but for the sake of understanding, I will just give a brief description. An assembly is a collection of types and resources that form a logical unit of functionality. In .NET, they can have .dll or .exe extensions. Assemblies can be shared between applications. Creation of an assembly is very straightforward. In fact, when you click Build on the Build menu, you are compiling your application and creating an assembly. Ok. It wasn’t so brief, was it?

Anyway, that’s enough for part 2 of this article. Hope you have learned the concepts of this part as they will act as the foundation for further study in part 3. Till then, happy coding.

History

  • 5th 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

 
QuestionGood Article Pin
Member 122110687-Jan-16 18:25
Member 122110687-Jan-16 18:25 
GeneralMy vote of 2 Pin
Member 122110687-Jan-16 18:24
Member 122110687-Jan-16 18:24 
Questionnice one Pin
mcdubey10-Feb-14 20:15
mcdubey10-Feb-14 20:15 
QuestionConfusing question Pin
Thornik12-Jul-11 2:09
Thornik12-Jul-11 2:09 
AnswerRe: Confusing question Pin
KeithAMS14-Jul-11 1:14
KeithAMS14-Jul-11 1:14 
GeneralRe: Confusing question Pin
Thornik14-Jul-11 1:49
Thornik14-Jul-11 1:49 
GeneralRe: Confusing question Pin
KeithAMS14-Jul-11 2:31
KeithAMS14-Jul-11 2:31 
GeneralMy vote of 3 Pin
Abolfazl Khusniddinov12-Jul-11 1:18
Abolfazl Khusniddinov12-Jul-11 1:18 
Questiondecent Pin
BillW338-Jul-11 3:13
professionalBillW338-Jul-11 3:13 

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.