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

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

, 7 Jul 2011
Rate this:
Please Sign up or sign in to vote.
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:

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:

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:

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:

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:

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:

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:

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:

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:

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.

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:

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

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

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:

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:

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:

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:

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:

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)

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

 
Questionnice one Pinmembermcdubey10-Feb-14 20:15 
QuestionConfusing question PinmemberMember 308248712-Jul-11 2:09 
AnswerRe: Confusing question PinmemberKeithAMS14-Jul-11 1:14 
GeneralRe: Confusing question PinmemberMember 308248714-Jul-11 1:49 
GeneralRe: Confusing question PinmemberKeithAMS14-Jul-11 2:31 
Glad to be of help!
KM
 
I'm pink therefore I'm Spam

GeneralMy vote of 3 Pinmemberafaz12-Jul-11 1:18 
Questiondecent PinmemberCIDev8-Jul-11 3:13 

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 | Mobile
Web03 | 2.8.140721.1 | Last Updated 7 Jul 2011
Article Copyright 2011 by Morteza Giti
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid