About mariocatch

I'm a school-taught Software Engineer graduate from Fullsail. However, what most people don't know about me is that I'm a self-taught astronomer, with a passion for astrophysics and the theoretical sciences in general. I'm going back to school to pursue a degree in physics to better myself as a software engineer. I hope to one day educate the masses in physics and chemistry using software as my chalkboard. I'm currently a Software Engineer at Electronic Arts and have been there since May of 2005.

Educational: Introduction to Classes (Part 2)


Previously, I spoke about classes in .Net (C# specifically) and how they can be used. We started off with a simple class called MyMathClass, which contained one method called Add. This method simply took two integers, added them together, and returned the result to whoever would be calling the method. Remember, methods are containers for logic. They are typically given some parameter(s) to work with and then go they do some logic with them. Methods can manipulate the parameters or use them to do other tasks. They can also return a value to whoever called the method. Methods are created to provide functionality to your program, however, a method is quite useless if no one is calling it. If you had a bunch of math methods in your math class, that doesn’t mean they are being used for anything. A method needs to be called in order to be used. Sometimes you create methods knowing they will be used a lot. Other times you create methods maybe not knowing if they’ll even be used at all. Classes can be libraries as well. A library in programming terms is a class or suite of classes that provide a common functionality when put together. If your boss comes to you and says, “I need you to write me a library that supports basic math functions.” then all your boss is really asking for is for you to create a class or bunch of classes that deliver basic math calculating functionality. You would probably create a math class that has methods for adding, subtracting, multiplying, and dividing. Then, you would deliver this class to your boss or team and say, “Here you go, here’s the library you asked for.” And hopefully there would be no errors in it!

Now I want to focus a little bit of time on how you work with classes. Like I said before, classes are great and all but if no one is actually using the classes you write then what’s the point?

Let’s go back to our example before of a class called MyMathClass

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

Just to review. We have a class called “MyMathClass” which contains one method called “Add”. This method takes two parameters (“leftHandOperand” and “rightHandOperand”), both of type integer. This method also returns an integer. Inside the body of the method is some logic that takes the two parameters given to it, adds them together, and returns it.

Now let’s create a program that calls this method by passing in two integers and getting the return value back from it.

If you remember my first hands on lecture then hopefully this is a somewhat of a refresher for you.

Follow these steps carefully so we all stick together.

  1. Open Visual Studio 2010 Express C#
  2. Go to File->New Project (or click Create New Project from the Start screen)
  3. From here click once on “Console Application” to highlight it (do not double-click it yet, if you did, repeat step 2)
  4. At the bottom of this dialog is a Name text box, give this project a name of “MyMathProgram”

You should now have a new project called “MyMathProgram”, which contains a class file called “Program.cs” (the default class added to Console Application project types).

Within that file should be a class called “Program” which contains one method called “Main” (the default method for all Console Application project types).

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Add logic here.
        }
    }
}

I added a comment in the body of the Main method to emphasize that we need to do something in there. A comment is a line that the program will ignore when it is running. Comments are really just ways for programmers to communicate with one another. It’s similar to a teacher writing notes on your homework for you to read later. To write a comment in C#, you start off with adding two forward slashes ( // ), then follow it up with whatever you want to say. Comments only work for one line at a time. If you want a multiline comment you’ll need to add another set of forward slashes on the next line. Comments are great and highly recommended for all developer levels. Comments are not just for beginners, sometimes code can be very complex and difficult to understand. Thanks to comments, a good programmer can add comments around their code so another programmer at a later date and time can pick it up and hopefully understand it.

Now let’s go ahead and create another file in our project. This file will be our math class from before which had the Add method in it.

  1. On the right-hand side of Visual Studio you should see a window called Solution Explorer (if you don’t, go to View->Other Windows->Solution Explorer)
  2. Find your project (“MyMathProgram”) and right-click on it
  3. Go to Add->Class
  4. At the “Add New Item” dialog, ensure Class is highlighted (don’t add it yet, if you accidentally did, delete the file from your Project by right clicking on it and selecting Delete)
  5. At the bottom of this dialog you’ll see a Name text box. Give this new class a name of “MyMathClass” (if you don’t specify a file extension, Visual Studio will automatically give it an extension of the file type you have selected in the dialog. Since we should have Class selected it will automatically give the file an extension of “.cs”. If you really want to, you can still specify the file extension and it will use it.

Now if you look at the Solution Explorer you should see that it contains not only the class we were looking at before, but it also contains the one we just added. By default, Visual Studio automatically opens up classes that are added to projects. So let’s go ahead and work with the class that is open now.

Let’s add our Add method back into this class.
We’ll go from this:

namespace MyMathProgram
{
    class MyMathClass
    {
    }
}

To this:

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

If you’re confused by this, please see part one of this lecture series. It contains all the information you should need about this class thus far.

So now let’s take a step back and think about what we have so far.

We have a class called “MyMathClass” which contains a method called “Add” which simply adds two integers together and returns the result as an integer.

We also have a class called “Program” which is the heart of our program. When execute this program it will find the Main method in the Program class, and run through it line by line until it gets to the end of the body.

We’re about to do a real example one of the most powerful concepts in programming in decades… object-oriented programming.

We know we have a class that can add two integers together. But how do we use it in another class? If you remember my first hands on lecture where you wrote your first program, then you should remember that in that program we were writing out to our command prompt window (console window) some string of text. We were able to achieve this by using a .Net class called “Console”. We invoked a method off of the Console class called “WriteLine”, which took one parameter… a string of text. That method is part of the .Net Framework, so it’s given to us for free. Calling that method and giving it a parameter is exactly what we are about to do right now with our program.

Let’s go back over to our Program class (double-click on the file “Program.cs” from the Solution Explorer).

We still have this in our Program class:

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Add logic here.
        }
    }
}

Now, just like when we used the Console class, we need to now use our own class, the “MyMathClass” class.
I’m probably going to confuse you here, but try to hang in there and I’ll do my best to explain it.

When we used the Console class to call the WriteLine method, we simply did Console.WriteLine(“blah”);
If you were to try and call our Add method from our MyMathClass class in the same way (MyMathClass.Add(1, 1);) then it would fail.

The reason it would fail is beyond the scope of this lecture. If you want to research it, you should look up static methods. A very basic definition of a static method is a method that does not require an instance of its parent class in order to be called. In the case of the WriteLine method from the Console class, WriteLine is a static method. I know it’s a static method because I can use it without creating an instance of the Console class. Creating an instance of a class is another key part of object-oriented programming.

Consider “creating an instance” synonymous to giving birth in real life. When you create an instance of something in programming, you are creating a NEW instance of that class or object. In the case of the WriteLine method, we didn’t create an instance of the Console class to call it. We simply said Console.WriteLine… There is no new instance of Console in that example, therefore the method being called MUST be static.

The reason why you create static methods is when you really don’t want more than one instance of the method to exist out there in the virtual world of your program. Sometimes, it just makes sense to only have one instance. Look at the Console.WriteLine example again. If WriteLine weren’t static, then you would have to create an instance of the Console class just to use the WriteLine method. It seems like overkill to me. WriteLine is a very basic method. It is writing some text out to the console window. In-fact, our Add method in our MyMathClass class is also very simple. It is indeed a good candidate for being static, but we won’t do that (yet). The reason it’s a good candidate to be a static method is because it has literally no dependency on anything outside of its own scope (scope in this case is the body of the method). The method takes two integers, adds them together and returns the sum. It is a perfect candidate for being a static method.

You’ll have better intuition in time and practice of when to use static and when to avoid it. Typically, you’ll use more instanced methods than static methods, but sometimes static methods work nicely.

Anyways, I know I said static is beyond the scope of this lecture and then I went off on a tangent explaining it, but it is indeed beyond the scope of this. I just wanted you to at least be able to look at that keyword and not be completely lost.

So, back to our program. The last thing I said before all the static talk was that until now we’ve only worked with a static method (WriteLine). Since Add is not a static method, we need to create an instance of the class in which Add resides in order to get access to it.

So let’s create an instance of our MyMathClass right now.

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            MyMathClass myMathClass = new MyMathClass();
        }
    }
}

Let’s dissect this line. It contains a word “MyMathClass”, followed by the same word but spelled differently “myMathClass”, followed by an equal sign, followed by the word “new”, followed by the same word again “MyMathClass”, followed by an open and close parenthesis, and ended with a semicolon.

First I’ll just say that this entire line is creating a new instance of our MyMathClass, and storing that instance in a variable called myMathClass (with a lowercase ‘m’ at the beginning).
We create instances of objects by starting out the line with the object we want to create an instance from… in this case, “MyMathClass”.
We then type out the name you want to give this new instance. It is common convention to name instances of objects the same name as the object itself, but with a lowercase first letter of the first word (this is called camel case, similar to the appearance of a camel… the first hump on its back is shorter and the next hump is taller, in our case, the first letter of the first word is small, and the first letter of every remaining word is big).

Unfortunately it’s not as easy as just giving your instance a name and ending it with a semicolon. In order to “initialize” your new instance, you must set your named variable to a “new” instance of the class you want to create an instance from. So, we add an equal sign to say, “I want to set my new variable EQUAL to a NEW instance of this class.”.

Now to the parenthesis… you might be asking yourself, “Ummm, why are there parenthesis on this class? It’s not a method… it’s a class!”.
I’m now going to introduce you to constructors. Constructors are pretty much exactly what they sound like. They construct things… in the case of programming, they construct objects. Constructors are methods, but with a catch. Constructors behave and act exactly like methods in every way except two (that are important). First, constructors must have the same name as the class (or object) in which they are constructing. Second, constructors cannot have a return type. What’s this mean? Does that mean it has to return void? No.. it literally means it can’t return anything, not even void (I guess you could argue that all constructors return void by default). If you add “void” in front of a constructor method then it complain when you try to run your program.

So now I hope you’re asking, “So if constructors are methods with the same name as the class they reside in, then how are we calling a constructor here called MyMathClass() when we didn’t even add it to our class?”. Great question if you were thinking that.

The reason why we’re able to call this method without it actually being there is because implicitly (behind the scenes, automatically), every object in .Net has a constructor by default. It’s invisible to you and me, but it’s there. In-fact, it even has a name… it’s called a default constructor. The definition of a default constructor for Java (another programming language, similar to C#) is actually very good. I’m going to paste it here:

In Java (programming language, a “default constructor” refers to a Nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class.The default constructor is also empty, meaning that it does nothing

This applies to our C# example as well. We didn’t define a constructor (method with the same name as the class it resides in) in our MyMathClass class, but one is there anyway by default for us. If you were to write a constructor in our class that had no return type and did nothing (empty body), you would be replicating the default constructor that was created automatically for us.

In-case you were wondering, a default constructor looks like this:

    class MyMathClass
    {
        public MyMathClass()
        {

        }

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

Notice it has the same name as our class, and an empty body. It also has open and close parenthesis because it is also a method. The only thing new here is the word “public” in front of it. This isn’t a return type, it’s the accessibility of this method. I will go into public on another part of this series on classes, but for now, just know that public means “anyone can access this member”, and private means “only my closest friends can access this member”. In this case, our class “Program” falls under the category of “anyone” and not “my closest friends”, so in order for us to create an instance of it we must declare this method as public.

Now then, back to our Program class.

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            MyMathClass myMathClass = new MyMathClass();
        }
    }
}

We should be pretty familiar with what is going on now. If any of it is rusty or blurry, simply re-read the parts above that pertain to where you are concerned.

At this point, we have an instance of our MyMathClass class called, “myMathClass”.
We can use this instance to access the non-static members of our MyMathClass class. Since we already know nothing in this class is static, then we can access anything from it (that’s public).

Oops, did you see what I just said? I just said that we can only access anything that’s public from our MyMathClass class. Why is that? I briefly explained before the difference between public and private in front of members of classes. In this case, Add is the member we want to get access to. If you go over to our MyMathClass class and look at the Add method, you’ll see that all that’s in front of it is the word “int”. Well, that’s the return type but that doesn’t help us any… You may be asking yourself, “Well if by default, the default constructor is public without telling it to be, shouldn’t everything else be public too?”. Actually, the answer is “no”. Nothing else is public by default. In-fact, everything other than a default constructor is private by default. Default constructors are the exception to the rule. If we want anyone to be able to access our Add method, then we’re going to need to make it accessible… and that means making it public (by the way, this problem that we’re running into now is another key component of object-oriented programming. It’s called, encapsulation. Imagine encapsulation as someone who is holding onto something else very tightly. They are encapsulating that object in their hands, keeping it private. If they wished, they could lessen the encapsulation and make it public for anyone to take. A person controlling the accessibility of the object in their hands in the same as a programmer controlling the accessibility of the objects in their code. You may not want to make everything private or public. Sometimes, exposing some members to the public, and keeping others to yourself is the way to go. Imagine if you had a class that knew some passwords to sensitive information. You probably wouldn’t want to make that public, because then all anyone would have to do would be create an instance to your class and voila… they can get whatever is public. If you kept that information private, then you wouldn’t need to worry because it’s safe from the outside scope of that class.

So before we are able to use our Add method, we need to make it public. Do so now:

    class MyMathClass
    {
        public MyMathClass()
        {

        }

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

Now then, let’s go ahead and access our Add method, and make it perform a 1 + 1 operation in our program.

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of our MyMathClass class.
            //  Store this new instance in a variable called, "myMathClass".
            MyMathClass myMathClass = new MyMathClass();

            // Call the Add method off of our new instance.
            //  Pass in 1 as the leftHandOperand,
            //  and also 1 as the rightHandOperand.
            myMathClass.Add(1, 1);
        }
    }
}

I added some comments to hopefully give an understanding as to what is going on in our program.
When this program is executed, only two lines will actually be seen by the program… the new instance creation, and the Add() call. The comments will be ignored by the program. They’re only useful for humans, not computers.

Let’s take a look at our new line we added. It starts off with our new instance of our MyMathClass class, and is followed by a period. Remember the period ( ‘.’ ) is how we say, “fetch me the following…”.
We’re basically saying, “Fetch me the Add method from this instance of the MyMathClass class”. We then follow-up the period with the method we want to call, in our case, Add. Inside of this call, we see a 1, a comma, and another 1. If you remember our Add method, it took two parameters, both integers. Well, you can see here that we’re giving our Add method two parameters, both integers as well. So this should be good to go.

We close off the method call with a close parenthesis and a semicolon.

Let’s go ahead and run this program and see what happens.
Press “F5” on your keyboard to run the program.

You’ll notice that once again, the program opened and closed almost immediately. I say “once again” because this happened to us before already, in my first hands-on lecture. The program is closing almost immediately because our Main method is executing the two lines of code it contains and then getting to the end of the body. Once it gets to the end of its body, then there’s nothing left for our program to do… so it exits.

Let’s add a line of code that we added in the hands-on lecture. This line of code will tell our program, “Hey, I know you want to quit, but just sit around and wait for the user to press the Enter key. Once that key is pressed THEN you may exit”.

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of our MyMathClass class.
            //  Store this new instance in a variable called, "myMathClass".
            MyMathClass myMathClass = new MyMathClass();

            // Call the Add method off of our new instance.
            //  Pass in 1 as the leftHandOperand,
            //  and also 1 as the rightHandOperand.
            myMathClass.Add(1, 1);

            // Tell our program to sit and wait for the Enter
            //  key to be pressed.
            Console.ReadLine();
        }
    }
}

As a quick side note, notice that there’s no instance of the Console class on that ReadLine() method call. You may recall what that means from earlier… ReadLine is a static method!

Anyways, now press “F5” on your keyboard and notice that the program opens and sits there and appears to do nothing (press F5 now).
Well I can tell you it’s not doing nothing, even though it may seem like it visually.

Our program is actually doing 3 things. It’s creating an instance of our class. It’s calling the Add method off that instance, and it’s waiting for the user to press Enter.
Go ahead and press Enter on your keyboard now to allow our program to exit gracefully.

Let’s do one more thing with this program to let the user know it’s actually doing something!
You see the Add() method call in our program? It’s adding 1 + 1 right now, but where’s the answer? Let’s let the user know the answer.

Since we have a Console Application project type, we can utilize the console window (command prompt) for printing out the result of our Add() method call.
Let’s do so now, after the Add() call, but before the ReadLine() call.

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of our MyMathClass class.
            //  Store this new instance in a variable called, "myMathClass".
            MyMathClass myMathClass = new MyMathClass();

            // Call the Add method off of our new instance.
            //  Pass in 1 as the leftHandOperand,
            //  and also 1 as the rightHandOperand.
            // Add returns an integer, so let's catch the return value
            //  and store it in an integer variable of our own.
            int sum = myMathClass.Add(1, 1);

            // Take the result of our Add() call and print it to the console window.
            Console.WriteLine(sum);

            // Tell our program to sit and wait for the Enter
            //  key to be pressed.
            Console.ReadLine();
        }
    }
}

I made a change to our Add() call and added comments to reflect that change. I also added the Console.WriteLine call.
So let’s go over these changes.

First, the Add() call clearly has changed. It now has the words “int” and “sum” in front of it.
As you know, “int” is short for “integer”, and is a recognized keyword in C#. We know that our Add() method returns an integer, which is the sum of the two parameters it is given, so this is our way of saying, “This method returns an integer, so I’m going to catch it here.” Now, when Add() is called with 1 and 1 as its parameters, the result of that call will be thrown into our little catch before it, which will be put into the variable we named as “sum”. We could have called it anything, but “sum” is a good choice for the answer to an addition equation.

Now that we have the result to our method call, we can print it out. We can utilize the WriteLine() method off the Console class for that (another static method!).

WriteLine was used in the hands-on lecture. We used it to write out some friendly message to the console window. In that case, the type of parameter we sent to it wasn’t an integer. It was a string. WriteLine() supports many different types of parameters, one of them being string, and conveniently another being integer. So we can pass our integer into this call and it should work just fine.

Go ahead and press F5 on your keyboard now to run the application.
If everything went well you should see a “2” at the top left of your console window!

If not, then go ahead and review the notes above on where you think something may have gone awry.

<closing>

Congratulations! We went over a lot of topics in this lecture. A lot of very basic foundation concepts that a lot of programming is built upon.
We went over classes in-depth, creating members in classes, constructors, encapsulation (public, private), creating instances of objects and using them in other classes, calling members off of an instance of an object, and statically by the use of static methods (the Console class’ WriteLine and ReadLine methods), and a whole lot more!

Thanks for reading, and as usual if you have any questions or comments, feel free to leave them here!

</closing>

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>

Educational: My First C# Program


Objective: Download the tools needed to develop your first program, then actually write your first program.

Tool(s) used:

Greetings,

I left off last post lecturing about C# and the .Net Framework. I spent some time going into detail about how the .Net Framework works, what types of software exists out there in the virtual world, and how I perceive C# to fit into the grand scheme of things. I also gave my opinion on C# and .Net and that I would be using them in my lectures. If your interest is in .Net and C#, then you’ve come to the right place.

I’m going to start off with the first hands-on lecture by showing how to download the software needed to write your first program, and actually go into detail to help you write your first program.

Let’s begin!

First, where do you think programmers write code? How do you think the code actually tells the computer to do something? When I first started, I wrote my code in notepad and ran a separate program to compile and execute that code… well, those days are long gone (and thankfully).

Microsoft has been releasing versions of a program called Visual Studio for over a decade now. Visual Studio (as the name suggests) is a visual aid in your pursuit of writing code. It provides a lot of useful tools and tidbits that allow you to do your job easier. Visual Studio is an IDE (Integrated Development Environment), which is a fancy way of saying, “the place in which code is written”. You simply open up Visual Studio, and begin writing your code. Periodically you run or test your code to make sure it works. When you’re all done, you compile your code into an executable and deploy the executable to your machine, your friends, family, or the world. Visual Studio is not the only IDE available. There are a lot of independent and open source IDEs available out there, but Visual Studio is an industry standard, and it’s free (the Express editions are anyways).

Step 1: Obtaining Visual Studio

Now we can begin by downloading Visual Studio 2010 Express (C#) Edition.

Navigate to http://www.microsoft.com/express/Downloads/#2010-Visual-CS

From there, select your language of choice within the “Select language…” ComboBox.

Visual Studio 2010 Express C# English Edition

From there, follow the dialogs on-screen to install Visual Studio 2010 Express C# Edition onto your PC. After the install is complete, you can continue on to the next part of this lecture.
Step 2: Creating Your First Project
Now that you have Visual Studio 2010 Express installed, find it on your PC (most likely your Start menu) and open it.
Proceed through to the Start Page. When you get there, it will look something like this:
Visual Studio Start Page
From here, you will proceed to create a Project. A Project in the context of Visual Studio is essentially a module of your program. It could be your entire program, or it could be one part of your program. A Project is the second highest housing container within Visual Studio. The highest container type is called a Solution. A Solution contains one or many Projects, and a Project contains code files. In the most simple case, you would have one Solution, which houses one Project, which houses your code files.
Click on “New Project” from the Start Page. Here you are presented with the “New Project” dialog. This screen provides you with a bunch of templates to choose from when creating a new Project. Like I said before, a Project houses your code files, and a templates shown here are just there to guide you in the right direction.
Here’s a brief description of some of the templates:
  • Windows Forms Application – Provides a template which when selected, gives you all the starter code for an empty Windows Forms application. Just gives you a basic Window with no controls on it aside from Minimize, Maximize, and Close.
  • WPF Application – Provides a template which when selected, gives you all the starter code for an empty Windows Presentation Foundation application. Just gives you the basic Window with no controls on it aside from Minimize, Maximize, and Close.
  • Console Application – Gives you all the starter code needed for a basic Console application. A Console application is an application that runs from start to finish (top-down) and then exits. It runs within a console (command prompt).
  • Class Library – Gives you an empty project with one class added to it (a class will be explained later). A Class Library project type is used when you want the Project to be used as part of an application, but not be the application itself (ie: a Reference).
  • Empty Project – Gives you a new Project with absolutely no code files in it.

For our first program go ahead and select “Console Application” and give it a name of “MyProgram”.

You’ll notice a few things take place.

  1. The “New Project” dialog closes
  2. A new Solution and Project have been added to the Solution Explorer on the right hand side of Visual Studio with the name of “MyProgram” on each of them
  3. A file has been added to the MyProgram Project called, “Program.cs”
  4. Program.cs has been opened and is ready for editing in the Visual Studio editor

So let’s look at each of these.

Step #1 is pretty expected behavior, but what about Step #2? Why is there a Solution AND a Project? And both with the same name? If you remember on the “New Project” dialog, you gave your Project a name of “MyProgram”. You were in-fact naming the Project and the Solution. You could have chosen to give your Solution a different name, such as “MySolution”, but for our sake it didn’t matter, and if you don’t explicitly tell it to change names, then it will use the same Project name for the Solution name.

Notice the two folders and one file under the MyProgram Project.

Properties and References are added to every Project by default. Properties contains some basic information about your Project (the properties of your Project). If you expand the Properties folder and notice the AssemblyInfo.cs file within it and open it, you’ll see a bunch of mumbo jumbo that essentially is just defining your new program’s version and such. At the bottom of that file you can see the assembly version. This is the same version that will show up if you were to right-click on the program in Windows and select Properties. Now, close out of AssemblyInfo.cs if you opened it (to close out of an opened file in Visual Studio, simply locate the tab with the name of the file and either click the “X” at the right hand side of it, or right click->close it, or simply middle mouse click on it.

The References folder, if you expand it, you’ll see contains numerous references. This may look complicated, but in actuality is a very simple concept. Think back before to the “New Project” dialog. Remember the choice on there for Class Library? I stated before that a Class Library Project type is only to be used when you want it to be part of your application, but not itself be your application. To better understand this, consider this example. Imagine you were creating a program that acted as a Calculator. You would create a nice looking UI that had nice buttons and such that any user could understand just by looking at it. However, it is considered bad programming if you simply put all of your math and calculation logic in the same Project. What if you one day created another program that could benefit from the math calculations you did in your calculator Project? That’s where Class Library Project types come in. A Class Library isn’t your application, but it can be used by your application. So, you could create a Math Class Library, and a Calculate Class Library, then you could re-use those in multiple programs! In order to use a Class Library Project type in another Project, the other Project must add a Reference to the Class Library Project. Remember that a Solution can contain multiple Projects. The Projects don’t just magically know about each other within the same Solution. Projects only know about other Projects that they contain a Reference to. So to go back to the References folder of your new Project here, you can see that it contains some References already. These References are to some very common Class Library Projects that Microsoft has provided for you. If you take a minute, you can actually right-click on the References folder, and select Add Reference. Go to the .NET tab and notice all the Class Libraries that already exist! Microsoft has added hundreds of them in the .Net Framework, and they are always adding more in updates. This is the glory of the .Net Framework. It has a lot of code written for you already, so you can re-use a lot of common tasks without needing to write the code each time! Go ahead and close out of the “Add Reference” dialog, and collapse the References folder.

Now let’s go on to Step #3 (“A file has been added to the MyProgram Project called, “Program.cs””)

Let’s dissect this file. Just by looking at it you can see its name. “Program”, followed by “.cs” .  “Program” is the name of the file added to ALL Console Application Project type templates. It really is your program. If you were to run your program, it would execute the Main method in there (we’ll get to that later). The “.cs” is simply the file extension. Just as files on your Windows PC have file extensions, so do code files. This one (“.cs”) simply means “class”. This is a class file. A class is a container of members. Going back to my example of if you were to create a calculator application, let’s say you wanted to create a way to handle all of the math operations in one location. This is where classes come on. You could create a new class (.cs file) called something like “BasicMath”, which had a bunch of different methods for adding, subtracting, dividing, multiplying and so forth. A class really is just a container for members of the class. In the case of our Program.cs file, the class is conveniently called “Program” (note: It is common convention to make the name of the file the same name as the class within it). And it is the container for our program’s heart. It contains a method called Main (which in our BasicMath example, could be something like Add, or Subtract), which is the heart of our application. When our application is executed, everything inside of Main will execute from top to bottom. When it hits the bottom of the Main method, the program will exit.

Looking at Program.cs some more, you’ll see a “namespace MyProgram” surrounding the class. A namespace is essentially a house to a class (or classes). You can have many classes within a namespace. It is common practice to name a namespace according to the folder hierarchy it appears in on the file system. IE: If your Project had the following structure:

MySolution

-MyProject

–Folder1

— Class1.cs

— Class2.cs

— Folder2

— Class3.cs

— Class4.cs

Then your namespaces for Class1 and Class2 would be something like, “MyProject.Folder1” and your namespaces for Class3 and Class4 would be “MyProject.Folder2”.

Namespaces are very helpful because they provide another layer of organization to your application. With namespaces, you can provide a naming scheme to different parts of your application, such as, “Calculator.Math”. This type of namespace would be expected to house a bunch of math related classes. Or “Calculator.UI”, would expect to contain the UI specific files for your application.

Looking back at Program.cs you’ll see it has some “using” statements at the top of the file. Remember the References information I provided you with earlier? A Project can contain one or many References to other Projects. However, just because your Project contains References to other Projects doesn’t mean that you can simply start using those other Projects’ classes. You must add a “using” statement, pointing to the namespace to use. That’s right, following the “using” keyword is the name of the namespace you want to “import” into the current file. Adding using statements to the top of your file doesn’t hurt your program any, but it’s not common convention to just go and add a bunch of usings up there.

Step 3: Writing Your First Line of Code!

Now let’s write our first line of code!

Since we know we have a Project of type Console Application (that’s the template we chose off the “New Project” dialog), then we know that when we run our application, it will present us with a command prompt window (console window), but just to be sure let’s run our program right now.

To run your program, simply press “F5” on your keyboard (or go to Debug on the menu up top, and select “Start Debugging”). If you have a quick eye you may have noticed a brief moment where a black rectangle was present on the screen and then disappeared. This rectangle was actually our console window… it was our program! If you look at the Main method in your class, you’ll see it has nothing in the body of it (the body of a method is everything in between the opening and closing curly brackets ‘ { ‘ and ‘ } ‘ ). Since our Main method is the heart of our application, and there’s nothing actually inside the Main method, then it is actually acting just as intended. It has nothing to execute so it simply just starts and then stops and closes right away.

To get our program to continue running without closing, we’ll add our first line of code!

In the body of the Main method, add the following line:

Console.ReadLine();

Let’s examine this line of code. It starts off with the word “Console”, followed by a period.

What you’re seeing here is the use of another class! In this case, the class we’re using is called “Console”. How do I know it’s another class? Well, Visual Studio has color coded the word “Console” for us in a light bluish color. This at least lets us know that it is recognized by Visual Studio. Another way I know it’s a class is that if I remove all of the using statements at the top of the file (try it now, just use your mouse to select all of them and press the backspace key on your keyboard), you’ll notice that the “Console” word we just added goes to black and a red squiggly line appears beneath it. This is your first sign of an error. Visual Studio is telling us, “Hey! I see you’re trying to use the word Console as a class, but we simply can’t find it!”… well, of course it can’t find it, we just removed the using statement that taught our class how to find the Console class! (press Ctrl+Z (undo) to get your using statements back). The using statement which actually houses the Console class, is “using System;”.

The period ( ‘ . ‘ ) after the Console class is used to tell our program that we want to access something from the Console class. If you remove the period and then add it back you’ll see a pop-up appear with ReadLine selected for you. First, the pop-up that appeared is called Intellisense. Second, it was defaulted on ReadLine because Visual Studio remembered that was the last thing you had selected (unless you copy+pasted my code snippet before). Intellisense is a very (very) powerful feature of Visual Studio (and all good IDEs out there). Basically, Intellisense is a visual aid to help you find what you’re looking for within a class. Do I remember every member of the Console class myself? Of course not… but I don’t necessarily have to – I have Intellisense to help me. I can simply just press the period button on my keyboard following a class (such as Console), and it displays to me a list of all the members of that class. A lot of them are pretty self explanatory as well and don’t require much research to find out what it means.

Then we have the words “ReadLine”, followed by an open and close parenthesis, followed by a semicolon. As Intellisense showed us, ReadOnly is a method off of the Console class. If you mouse over practically anything in Visual Studio, Intellisense will provide tool tips as to what it does. In our case,  ReadLine will wait for user input into the console window (command prompt). Once it has the input, it will continue over that line to the next line. In our case, there is no next line, which is exactly what we want. We want this ReadLine method to sit there and wait for us to press Enter on our keyboard. ReadLine waits for a new line of text to be entered into the console, and when we press Enter, we are sending a new line of text (even though it has nothing on it). Going back to the line of code, the ‘ ( ‘ and ‘ ) ‘ after the ReadLine method are how we actually execute the method. Notice how Console does not have parenthesis after it, but ReadLine does. Well, that’s because Console is a class, not a method. ReadLine is a method, therefore in order to call it (execute it/run it), we need to follow it up with a pair of open and close parenthesis. Then we follow that up with a semicolon ‘ ; ‘. A semicolon is how we end each line of code in C#. It is how we tell our program, this line of code is done, and I am stating so by ending it with a semicolon. If you remove the semicolon (do so now) you’ll notice that a red squiggly line appears after the ReadLine method call. This is because Visual Studio is telling us “Hey, we can’t find the end of this line of code! You may want to consider adding a semicolon here!” Add your semicolon back in.

Now that we have dissected this one line of code, you can take the same steps and dissect other lines of code that you’ll see in the future. Some are more complex than others, but when you learn the basic principle behind most of them, you can figure out the rest on your own.

Let’s run our program again and see what happens… Press “F5” on your keyboard.

Notice how the console window comes up and stays there now! This is not magic… it’s Console.ReadLine();! What’s happening is just as I described above – the program (a console window) will exit when it gets to the end of the Main method. Well, we aren’t letting it get to the end so fast anymore. We’re telling our program to sit there and wait for a new line to be entered into the command prompt. Ok, we can go ahead and send a new line in now… press Enter on your keyboard to send our program a new line. As soon as you do that, you’ll see that the window closes.

We’re almost done! Let’s say something in our console window before we decide to close it.

Go ahead and add a new line or two above the Console.ReadLine statement (remember, we want the Console.ReadLine call to be at the end of our Main method, and if we add any logic to our program, we want it to occur before the Console.ReadLine call, otherwise we simply won’t see it until ReadLine is executed, in which case the program would just reach an end and close before we even noticed.

Now let’s add a message to the console window. Let’s make it say, “Hello, welcome to my first program!”

Since we already know the Console class has a way to Read a new line from the keyboard, we can probably make a guess that it also contains a way to print or write something out into the console as well. Well, it sure does!

Add this line of code to your Main method.

Console.WriteLine(“Hello, welcome to my first program!”);

Let’s finally dissect this last line of code for this hands on tutorial.

It contains the following parts; “Console.”, which we already know is saying we want to access a method or member off of the Console class. Then we see WriteLine, followed by an open parenthesis, followed by some string of text, followed by a close parenthesis… Hmm, this looks a little different from what we’ve seen so far in method calls. Why is there stuff in between the parenthesis this time? Well, that stuff in there is what we call a parameter. A parameter in the context of programming is quite similar to a parameter in most types of uses in the world. It is simply an input variable into a problem or equation of some sort. In our case, the if you mouse over the WriteLine method, you’ll see that the tooltip that appears contains the words, “string value” wrapped around the parenthesis following the word WriteLine. what this tells us, is this method, WriteLine, expects one parameter to be a string. A string is a series of letters and/or numbers, it’s just a bunch of characters on a keyboard. The word “value” is not important, it could say “string blahfoobar” and all you have to worry about is the fact that it expects a string. blahfoobar in this case would just be the name they are giving this parameter. In our case, they named it value, but it doesn’t matter. We know that we need to pass a string as a parameter to WriteLine. If you mouse over WriteLine again and read the description of what it does, it simply tells you that it takes the specified parameter (value) and writes it to the standard output stream (the console window) and automatically adds a new line character at the end of it. But we could’ve guessed that already since it has the word “Line” in the name of the method… meaning, I’m going to Write a Line of text (typically a line in the world of text consists of a new line character at the end of it, don’t worry about this for now if you’re confused). Now that we know our WriteLine call expects a string as a parameter, we can give it the string we said we would earlier… “Hello, welcome to my first program!” (string parameters must be surrounded in quotation marks, just pretend that a string is actually someone saying something… you are quoting what they are saying by wrapping it in quotations.

And then last we follow it up with a semicolon to say this statement is complete.

Now, go ahead and run your new program and you’ll hopefully see the text we told it to say! Press Enter on your keyboard and the ReadLine() call will get hit and continue on to the end of our Main method, which finally closes the window which ends our application.

That’s it!

<closing>

In this tutorial we walked through downloading Microsoft Visual Studio 2010 Express Edition (C# – English), learned about the Visual Studio IDE, created a new Project, learned about the Solution and Project layout and relations, learned about the Project properties, References, and class file type, learned about what a class is, what namespaces are, what a using statement is, what methods are, how to call them, and how to write some text into a console application (among many other things were learned hopefully).

I hope you enjoyed this and if this is indeed your first time with Visual Studio, C#, or programming in general, I hope it was easy to follow.

As always, you can contact me by email or by leaving comments here.

Good luck!

</closing>

Educational: Why C#? What is the .Net Framework?


Greetings,

I stated my new initiative is to educate the masses, so why not start with the place in which the masses at one point also began?

C# (pronounced C-sharp) is a programming language developed by Microsoft. C# is written against a framework called the .Net Framework (pronounced, dot net framework).

All this means is that out of the box C# comes with a lot of functionality built-in for you. The .Net Framework is essentially just as it sounds. It’s a collection of tools to help you do your job more easily.

You don’t need to reinvent the wheel, and the wheel is the .Net Framework.

<tech speak>

When you write code against the .Net Framework, it is compiled into another language called an intermediate language. In-fact, C# is not the only language under the umbrella of the .Net Framework; there’s VB.Net, C++.Net, F#, A#, P#, and many more (complete list here). When you write code in any of these .Net languages and compile it, the .Net compiler turns your human readable code, into the less human readable intermediate language. This language is complex, but can be interpreted and transformed once again into native code (or machine code). The glory of this process is what allows 5 developers, all using different languages targeting the .Net Framework to work on the same project at the same time (not that this would happen often).

</tech speak>

So with all of these other languages out there, why choose C#? Why even choose the .Net Framework for that matter?

Both good questions, and both have complex answers.

Myself being a C# developer, am a little biased. However, from my experience over the past 6 years, here’s what you should know.

If you’re wanting to work on intensive, high performance video games targeting the popular platforms out there (PS3, Xbox 360, Wii), then C++ is the language you should learn.

If you’re wanting to get into phone development, then depending on the platform you choose, iPhone = objective C, Android = Java, Windows Phone = .Net (C#, Silverlight).

If you’re wanting to work on web development, then you have a lot of avenues you should investigate (HTML, CSS, Javascript, Flash, Silverlight, PHP).

There’s a lot more fields and languages to suit them, but the last one I’m going to talk about is tools development. What is tools development? What is a tool? Well, aside from that guy in highschool that wore his football jersey every day, a tool in the context of software development is an application that aids another person. Consider it analogous to a tool you would pick up out of a work shed to aid yourself in some home improvement task. Tools are an amazing asset to software development. A tool could be developed for internal use within your company or team, or it could be developed and released to the public. Microsoft Word is an example of a tool in the public. In-fact, all of the Microsoft Office suite applications are tools.

In this day and age, quick turn around time is important for tools and application development. Remember the .Net Framework that I mentioned before? Well, it comes with a ton of building blocks out of the box to assist you in getting your job done faster. For this reason among many (read… many) others, and the simplicity (arguably) of the .Net Languages (most notable, C#), the .Net Framework is a perfect choice for tools and application development. It is also a great way for first time programmers to jump in and get their feet wet with software development.

There is always market research being conducted on where the jobs are geared towards in programming these days. I can tell you that familiarity with the .Net Framework is a plus in a lot of companies out there. I haven’t seen every job, but I have casually job hunted over the past few years and the market never ceases to amaze me with its plethora of jobs targeting the .Net Framework.

<closing>

I hope you were able to take something away from this. I wanted to talk about C# and the .Net Framework first before I lectured on coding. If you had familiarity with this already, then I hope it was a refresher for you. If this was all new to you, then I hope this was helpful in aiding you in deciding what path to take next.

In any case, if you have any questions, feel free to email me or leave a comment here.

</closing>

New Initiative


I’ve decided to take a new initiative with this blog. In light of my recent endeavors into filling my brain with knowledge from the maths and sciences, I’m going to follow suit and extend my ‘knowings’ onto the internet.

Consider this blog my canvas, my keyboard the ink, my mouse the quill, and hopefully you, my audience.

Each post will declare a subject or topic and then continue on to delve into said area in an educational format. My end goal is to educate not only those reading, but myself as well.

I will hit on topics that start at early beginner level .Net concepts, and move into advanced topics such as WCF, SQL, and more. Whether you consider yourself an intermediate or absolute beginner, my goal is to have something of use for you here.

I look forward to this new goal and I will research a beginner level topic as my first post.

Look for my first teaching, coming soon.