Educational: Introduction to Classes (Part 1)


I spent some time in my previous post going over classes and how they interact with your program. The topic of classes are worthy of an entire lecture on their own… thus the reason for this lecture.

Let’s take a look at the definition of a class: A class defines constituent members which enable class instances to have state and behavior.

Similar to most computer programming definitions, this is pretty complex and hard to understand, especially if you have no idea what states or members are. However, we can break this down so it is easy to understand.

A class typically goes along with the programming paradigm called object-oriented programming. Object-oriented programming is a style of programming in which your program contains relationships between the objects within it. An object in programming would be something like a class called Math. The Math class (also called, Math object) would most likely contain a bunch of members that do math operations such as add and subtract. Now let’s say you wanted to use this Math object (class) in your application, which was a calculator. This is where object-oriented programming comes in. Your calculator application would use the Math object’s methods for adding and subtracting in order to add and subtract numbers for the user. The fact that the calculator is using the Math object to do the math calculations is the definition of object-oriented programming.

Let’s create a class here and then dissect it.

class MyMathClass
{

}

So here we have the word “class”, followed by a space, and then the word “MyMathClass”, followed by open and close curly brackets.

First, the word “class”. This word is a keyword in the C# language. You can tell it’s a keyword because it’s highlighted in blue (by default). A class is essentially an object. In the example from earlier in this post I talked about a Math class that had a couple of methods in it for adding and subtracting. A method is essentially a container for logic. When you create an Add method, you would expect it to take two numbers, add them together, and give you back the sum. When you create a Subtract method, you would expect it to take two numbers, subtract them from each other, and return the new sum. This process of adding and subtracting is the logic, and it is held within the container of the method. The method is containing the logic. More on methods later, but for now, back to classes. Everything in a class is a member of that class. So, a class is full of members. Methods are members. Properties are members. Fields are members. Everything in a class is a member. If you have 50 methods in your class, then you have at least 50 members in your class.

Second, we have the word, “MyMathClass” following the class declaration. This is the name of our class. We could have called it anything… but it’s typically a good idea to name your classes so they can be easily understood without having to see all the different members. If someone looks at this name, it is pretty apparent that this is a class which contains members pertaining to math.

Last, we have the open and close curly brackets { }. Any type of container in code needs curly brackets beneath it. Curly brackets define the body of the container. Without curly brackets, it would be very hard to read and understand the code. By looking at our class, you can easily identify that our class is called MyMathClass, and that is has an empty body. Methods are another type of container which needs curly brackets beneath it. Namespaces are another.

Now let’s add a method to our “MyMathClass”. Go ahead and add a method called “Add”.

class MyMathClass
{
     void Add()
     {

     }
}

We should already be familiar with the first line. It is the same class declaration that we had in the first example. But now we can see that our class contains a new member… the Add method!

Let’s dissect this method line by line.

First, we have the word “void”, followed by a space, then the word “Add”, followed by an open and close parenthesis, and beneath all of that are open and close curly brackets.

Well, we should already be familiar with the curly brackets. They are the body of our method. We should also be familiar with the word “Add” in there… because we named it! It is the name of the method. What sort of math object would it be if it couldn’t add?!

So let’s look at the word “void”. What is this? Isn’t void a vast nothingness? An empty abyss? Just… nothing? Well, actually yes it is. Void literally means, nothing in programming too. Think about addition. What is the most simplest form of addition? Well, typically it’s “1 + 1 = 2”. Break down that equation. It has a “1”, a “+” sign, another “1”, an “=” sign, and a “2”. The first “1” is the left hand operand. The second “1” is the right hand operand. The sign in between them is the operation to perform. And the last number in the result of the preceding operation. So to put it more simply… we have two parameters, an operator, and a result. How can we change our Add method to fit that scenario? Well we know that sometimes you can add more than two numbers together… but what remains the same? What is the constant in addition? There will always be ONE solution. There can only be one answer to an addition problem. So, take a look at our Add method. Remember the leading “void” before Add()? There are two types of methods in programming (typically). Methods that return nothing, and methods that return something. In our case, we want the Add method to return us the sum of the two parameters. The word that precedes the name of the method in C#, tells you what the “return type” will be for that method. So right now, our Add method is telling us, “I am going to return void when I execute.” Well, that does us no good. We need it to return something! What is the number “1”? Other than being very simple… it is a positive integer. Keyword, “integer”. Say it again… “inte”… “ger”. Integer means exactly the same thing in math as it does in programming. So what do you think we should change about our Add method now that you know what void means, and what our return type should be? You may have guessed it!

class MyMathClass
{
     int Add()
     {

     }
}

Of course, the glaring difference is in C#, the key word for an integer type is “int”. Subtle difference, and it should still remain easily recognizable. Some different return types are “int”, “string”, “decimal”, and many (many) more.

So far we’ve learned how to declare a class, how to add a method to a class, and how to decipher what the return type of the method is and when we should use void or change it (remember, use void if you want your method to return nothing).

Now remember Visual Studio is a compiler as well as a visual aid to help you write code. Right now if you were to add this class with this method to Visual Studio it would complain. It would put a red squiggly under the Add method and tell you, “Hey, you told me this method should be returning an integer, but it’s not!” Well, Visual Studio is right. We haven’t actually taught our Add method how to return anything yet… but don’t worry, we’ll get to it soon.

So now we have a class with a method that we want to eventually add two numbers together, and return a sum. Where do you think we are going next? A couple of sentences ago I mentioned “…eventually add two numbers together…” That’s exactly where we’re going.

Now, we have a method for adding something… but where is the something? If you recall from earlier when I broke down the “1 + 1 = 2” equation, the two “1”s were our parameters to the equation. They were our inputs. Well, let’s learn how to add parameters to methods.

Parameters are very powerful. They can literally be anything. But for our simple case, we know that we want to just add two numbers together and return the sum. So, those two numbers will be our parameters. We also know that our return type is of type int, or integer, so we should also make our parameters integers as well (adding integers is very simple, and since our method is expecting to return an integer, we may as well stick with that scheme).

class MyMathClass
{
     int Add(int leftHandOperand, int rightHandOperand)
     {

     }
}

Let’s dissect this method call now. First we have the “int” return type, followed by the name of our method, “Add”. Next you can see we added some new stuff in between the what used to be empty parenthesis following the name of our method.

First, I’ll say that all parameters to methods are separated by commas. You can see here then, that there is one comma in our parameters list, so that means that there are two parameters. The two parameters, I tried to name conveniently for you are “leftHandOperand” and “rightHandOperand”. We stated before that we wanted to keep working with integers, so we made sure to state that each of these parameters is of type int, or integer.

The name we gave the parameters could have been anything. It’s just a common courtesy to anyone reading your code to name things so they could quickly glance over it and understand it. Anyone looking at this method can quickly see that it’s a method that returns an integer and takes in two integers. The name of the method is “Add” and the two parameters are “leftHandOperand” and “rightHandOperand” so it should be easy to come to the conclusion that this method will add the two parameters together and return the sum.

To speak more on parameters, remember my example before of the simple equation (1 + 1 = 2)? Why didn’t we just put a “1” here? Why did we use parameters? Well, we are creating a math class with an add method in it. It wouldn’t be very reusable if MyMathClass had a method to Add in it, but all it did was “1 + 1 = 2”. We use parameters instead to allow the person using this method to define what the integers should be. They can add “1 + 1”, or they can add “187 + 142”. That’s the power of parameters. We define the constraint (only integers are allowed), and they define the specifics.

So now that we have our two parameters it’s time to do some logic!

class MyMathClass
{
     int Add(int leftHandOperand, int rightHandOperand)
     {
           return leftHandOperand + rightHandOperand;
     }
}

Taking a look at our Add method now, we can see that it contains some logic in the body. Remember before when I mentioned that Visual Studio was complaining that our Add method expected an integer to be returned but it wasn’t returning anything? Well, with this latest update to our method we are satisfying that need now. We know that our method wants an integer back, and we know that our two parameters given to us are integers, so we use the “return” keyword to state, “Everything following this ‘return’ keyword is what I want to return from this method”. A return keyword and the code right behind it are the last things a method will execute. When a method sees a “return” statement, it immediately says, “Ok, let’s gather up what this return statement is telling me to, and get on out of here!” In our case, we can use the conveniently named parameters that were given to us, and do some very simple math on them, then return the result. So we’re saying, “I want to return the answer of the following equation.” And lastly we follow it off with a semicolon ‘ ; ‘. Like stated in previous lecture, semicolons are how you end statements in C#. This semicolon is ending the return statement.

Whoever calls this method will be able to capture the return value from it and store it in an integer!

That may seem like a lot, but I really do hope it was conveyed in an easy to understand manner. This is a very simple, yet very powerful and informative example of a method.

<closing>

I had one more topic I wanted to discuss, but I think this is enough for one go around. I urge you to mess around with the code so far and play with it. I know I haven’t taught you how to actually use this class and method, but you can still change the input and return types of our method. You can try working with decimals instead of integers.

Next lecture will be a continuation of this one, and talk more about classes and different types of members that exist within them (Properties and Fields).

Thanks for reading, and if you have any questions or comments, go ahead and email me or comment here and I’ll get back to ya.

</closing>

Advertisements

One thought on “Educational: Introduction to Classes (Part 1)

  1. Pingback: Educational: Introduction to Classes (Part 2) | mariocatch on .Net – WPF – VC#

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