Freelance Writing Jobs | Today's Articles | Sign In

 
Browse Sections

A Closer Look at C# Classes - Part 2


Every once in a while we collect items, things and objects that interest us and often times we get attached to these objects that it is hard to let go. As humans, we put sentimental values on our possessions. You're starting to wonder if this is the C# topic here at Suite101.com. Rest assured, you've come to the right place.

If we look around our world, every object that we can see and touch has attributes. If we take a normal VCR as an example, you'll notice that a VCR can play videos in either NTSC or PAL format, maybe even both. Some of the high-end VCRs play stereo and have multiple heads. Another attribute of the VCR is the standard buttons for Play, Record, Stop, Pause, Forward and Rewind.

You can gauge a good programming language by how close and natural it can model the real world. C# supports class members to describe object attributes. Listing 1 is a representation of a VCR in C#. The program itself does very little, but presents a few concepts about classes in C#.

Listing 1
class MyVCR {
int m_numHeads;
int m_Format;
bool m_Stereo;
bool m_Paused;
string m_Brand;
// -- constructors
MyVCR() {
m_Paused = false;
}

// -- destructors
~MyVCR() { }

Play() {
System.Console.WriteLine("Playing video.\n");
}

Forward() {
System.Console.WriteLine("Playing video.\n");
}

Rewind() {
System.Console.WriteLine("Rewinding video ...\n");
}

Stop() {
System.Console.WriteLine("Video stopped.\n");
}

Pause() {
if ( m_Paused ) {
System.Console.WriteLine("Resuming play ...\n");
m_Paused = false;
}
else {
System.Console.WriteLine("Paused.\n");
m_Paused = true;
}
}

Record() {
System.Console.WriteLine("Recording ...\n");
}
}

In C#, you can declare internal variables to represent attributes of an object. If you look at the existing VCR market, you'll notice that some have two heads, four heads and six heads. The m_numHeads variable captures this attribute. In Listing 1, we've defined several internal functions to represent the buttons of a VCR. In object-oriented terms, these functions are sometimes called methods.

In C++, the only method to change or set a private class variable is to write a function. In C#, you can still continue to do the same or you can take advantage of properties. To get a better understanding of the rationale behind properties in C#, you'll notice that in most GUI environments, buttons are everywhere. These GUI environment support captions or text on the button to give the user some indication of what the button will do. It would therefore make sense to define a button class with a caption as a property.

The copyright of the article A Closer Look at C# Classes - Part 2 in C# Programming is owned by Jose Aniceto. Permission to republish A Closer Look at C# Classes - Part 2 in print or online must be granted by the author in writing.

Go To Page: 1 2

Articles in this Topic    Discussions in this Topic