Object Oriented Programming Part 2: Classes in Depth

In part 1 we discussed what an object is. For a brief review, an object is an instance of a class. A class is a file with code in it.

In today’s post, we will cover classes more in depth. If you recall the Chair class example, it only contained properties. Classes can also contain methods, fields, and member variables.

Let’s look at these items in more detail.

Before we delve into properties and methods, let’s take a look at access modifiers. They are a key feature of OOP because it allows functionality be encapsulated in a class.

Access Modifiers

MSDN article can be found here
public Anything can access the type or member.
private Only code within the same class can access the type or member.
protected Only code in the same class or struct, or any class that inherits that class can access the type or member.
internal Only code in the same assembly can access the type or member.
protected internal The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

What would happen if we changed one of the properties in the Chair class to private?

Properties

In the sample code we covered in part 1, the Chair class employed auto-implemented (or “auto” for short) properties.

First of all, though, what is a property? From MSDN:

A property is a member that provides a flexible mechanism to read, write, or computer the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Let’s break down one of the properties we used in the Chair class from part 1.

public string Type { get; set; }

The first part is the access level: public. This allows any class to access this property.

The second part is the return type: string. Every property must contain a return type.

The third part is the name of the property: Type.

The last few parts: { get; set; } are what is unique to a property. “get” simply returns a value. “set” sets a value for that property.

This type of property is called an Auto-Implemented Property. From MSDN:

[A]uto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property…the compiler creates a private, anonymous backing field that can only be accessed through the properties get and set accessors.

We could have rewritten the Type property to explicitly get and set a private field.

// Implementation without Auto-Implemented Properties.
private string _type;

public string Type
{
      get { return _type; }
      set { _type = value; } // value is the string being sent into the property.
}

Both implementations are equivalent.

Methods

A method is similar to functions or procedures from other languages. It is a code block the contains a series of statements. From MSDN:

A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method. The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started.

That last part regarding the Main method is important. Let’s refer back to the example from part 1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace MyChairConsoleApplication
{
    class Program
    {
        static void Main(string[] args) // This is the Main method!
        {
            var myChair = new Chair();
            myChair.ChairColor = Color.White;
            myChair.Height = 20;
            myChair.Width = 15;
            myChair.Type = "Office Chair";

            Console.WriteLine("The chair is a {0}. It has a {1} color, is {2} inches tall, and {3} inches wide.", myChair.Type, myChair.ChairColor.Name, myChair.Height.ToString(), myChair.Width.ToString());
            Console.ReadLine();
        }
    }
}

Notice the Main method, which takes in a string array of args (in a console application args are sent in from the command line). When a C# application is executed, this method is run first.

Let’s change a property from the Chair class into a method that returns a string.

// This was previously public int Height { get; set; }

private int _height;

public void SetHeight(int height) { height = _height;

}

public int GetHeight()

{

return _height;

}

To be able to use this method in the application we wrote in part 1, we would simply change the line

myChair.Height = 20;

to

myChair.SetHeight(20);

When we want to access that height value, we would call the GetHeight method in the Chair class.

Console.WriteLine("{0}", myChair.GetHeight());

Fields

A field is simply a variable that is declared in the class. the private variables we used in the code above are fields.

Members

Anything the resides in a class is a member. For a comprehensive list, refer to MSDN.

For practice, play around with the Chair class to see what happens when you change access modifiers, add or remove methods, etc.

The best way to learn is by hands-on practice. Don’t be afraid to break it!

The next post in this series will cover inheritance, encapsulation, and polymorphism in detail.

If you have any questions, comments, or suggestions, please do not hesitate to let me know in the comments!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s