Japy's C# Tutorials :: Part 1 :: Backgrounds and basics

Published:
Introduction
Hi all and welcome to my first article on Experts Exchange.
A while ago, someone asked me if i could do some tutorials on object oriented programming.

I decided to do them on C#. Now you may ask me, why's that?
Well, one of the reasons was that i have more C# than C/C++ knowledge.
Another one is that C# is becoming more and more a very important language, and forces you to think object oriented, wich is a style of programming were lots of people who are used to traditional techniques have trouble understanding with.
And last but not least, when you combine C# with the powerfull Microsoft XNA Framework it becomes fairly easy to create games that work on both PC and Xbox and even on Windows Phone 7.

Also, i decided to write them, instead of making video's.
Video's are handy, but not that functional when it comes to programming (imo). When you want to explore something in between, you have to pause them, remember where you were, you need audio so not development in the middle of the night with your wife sleeping next to you and lots of other downsides.
Also my English pronouncing is far from perfect.
Maybe i will make a video sometime when i really want to show something special, but changes are low.

I'm not a fulltime software developer as i'm also responsible for a part of the network management in the company where i work, but i'll try to do my best to make things as clear as possible for you all.
If someone finds an error in my ways of explaning or thinking, please let me know, as we both can learn from it :) also, if anything is not clear or you have a specific request, please let me know.

Requirements
For who is this tutorial?
This tutorial will be primary designed for people who have little to none experience with C# and/or Object Oriented Programming in general.
I do expect you to have little general knowledge about programming, as i'm not willing to explain basic stuff as what an array is, where you can find your console and more, but, when something is not clear, please ask me about it.

What do i need?
You will need to have Visual C# Express Edition 2010 installed.
This development suite is free (registration required to use it more than 30 days) and can be downloaded from Microsoft at Microsoft Express Downloads - Visual Studio Express and SQL Server Express.
Also you will need to run Windows XP or newer, but that seems pretty obvious.

What can i expect?
First i will focus on learning the whole Object Oriented Programming idea.
Don't expect to be programming Xbox 360 games in a week, also don't expect to become an awesome coder by reading these tutorials.
These tutorials are intended to make you interested, because the world needs more developers!
Also, if you become a millionaire because you created something with the knowledge gathered here, i want a 20% share of it.

Object Oriented Programming
So, what's OOP?
I guess most of you already heard about it, or even played with it.
For those who are already familiar with this style of programming, you can move on if you like, or read on to get an introduction to the way i will try to teach you. :)

OOP stands for Object Oriented Programming, an that's exactly describing what it is.
Now what is an object? Look around you, there should be enough of them.
For example, your computer's keyboard is an object, but also the plant on the sill plate beneath your window is one.
Your coffee cup, but also the coffee within it. Your wall, the stones in your wall, the sand in the stones, everything that exists is an object.

But, as you might say, no two stones are the same.
That's right, objects might have properties that make them differ. For example, take two coffee cups. What are the properties of them?
There are lots: material, color, sizes, handle, contents (coffee, tea, etc) and so on. In the 'real' world where no thing is the same, there are almost infinite properties to every object.

Maybe one of you did read the book Sophie's world.
In one of the chapters, the philosopher asks Sophie: "how can a baker make 50 exactly the same cookies?".
The answer was pretty easy: by using the same mold.
Let's take gingerbread men for an example.
Sure, they are different. Some are missing an arm, others are burned on the edges as they where closer to the grill, but what counts is that they are gingerbread men.

Take humans, we are all the same, aren't we?
Sure we have our own properties: skin tan, height, weight, etc etc etc...

This is the idea that OOP embraces.
We have a general 'idea' wich can exist multiple times with different properties, but it's still the same idea.

In OOP such an idea is named a 'class', and every version of it is an 'instance'.

To give an example, say, we want a game with two players.
Then we should create a class named 'player'.
What would be the properties of the player?
Think about:
 - Name
 - Age
 - Score

I will stop there to keep it simple, but there are more things you want to define for each player. Think about keyboard controls for example, one of them uses the arrow keys and the other wasd.

So now i need two instances, and give them their properties.
I first create 'player1' wich is an instance of the 'player' class and i give it these properties:
Name: Jill
Age: 14
Score: 0

Next i create 'player2' wich has already been playing this game a few times, and i give it these properties:
Name: Jack
Age: 15
Score: 3273

Now, in my program, i might want to request the name of player1, to show it's her turn to play, for example.
I'll ask the instance of this class nicely for it, by requesting player1->Name. Also i can request player2's name by asking player2->Name.

Next, player1 wins the match with a score of 800, i would set player1->Score.

Now those are the properties, but there's one more thing to them.

Don't much things in life have functions also?
I guess that would be nice, otherwise your lighter would have lots of nice properties, like, how much gas is in it or so, but no way to use.
So, to think of a lighter in reallife, you might have a 'use' function, and also a 'refil' function.
Your little sister might have a 'sniffmydirtysocksifyouwantsomecandy'-function, wich might even be poorly coded, as it triggers the 'complainandwhineatmom'-function, wich has nothing to do with it.

Now in your code, these functions would also be nice.
For example, Jack becomes sick, and handles his controller to Tim, who is standing there doing nothing.
Now there is a problem, as player2 is named Jack, so Tim wants to change the player's name.

There should thus be a SetName-function, or something like that.
Well, that's possible.

The common functions that are usefull for all players should also be created in the player class.

When that is done, Tim should be able to player2->SetName("Tim"); and be happy.

Now the SetName function (wich is'nt the best name for a function like this, but that aside) should do anything that's needed to change to another player.
For example, reset his score and restart the game, or, return his keyboard controls to default, or, ask him for his age, or at least initiate these actions, so they can be completed by other functions in this, or another class.

As you should understand by now, that when programming this way, the whole design of an application changes but is also much more flexible.

In the classic way, one would create structures (structs) that have these contents, or just plain variabeles.
Also these code with all it's functions would be very focussed on those two players, and when you want to make another million by bringing a 3rd player expansion pack, require a lot of work.

But how would a class like the one described here look in C#?
Here is a little code example:

class player
                      {
                      	public string Name;
                      	public int Age;
                      	public int Score;
                      	
                      	public void SetName(string NewName){
                      		this.Name = NewName;
                      		this.Score = 0;
                      		//do even more stuff
                      	}
                      }

Open in new window


There are some things where your eye might fall on.
The most important is the 'public' keyword.
What does this mean? It means that this property or method (the correct name for a function in a class) is accessible from outside the class.
There are a few other keywords, for example 'private', wich is only accessible inside the class, 'protected', wich is only accessible inside the class itself, or derived classes (we get to that later, forget it for now) and 'internal' wich is only accessible inside it's own assembly, we also get to that later, forget it for now.
If you already want more information on this topic, check out this page over at Microsoft MSDN.

Especially when you are not the only one working on a project, you sometimes want property's or methods that are'nt accessible from the outside, as they are not designed to be.
For example, you might not want to make the 'Score' setting public, but private and then create two methods GetScore and SetScore, wich allow you go read and set it.

Why would one do that? Well, you might want to make a check that a newly set score is never lower than the current one, thus doing something like this:

class player
                      {
                      	public string Name;
                      	public int Age;
                      	private int Score;
                      	
                      	public void SetName(string NewName){
                      		this.Name = NewName;
                      		this.Score = 0;
                      		//do even more stuff
                      	}
                      
                      	public void SetScore(int NewScore){
                      		if(this.Score < NewScore){
                      			this.Score = NewScore;
                      		}
                      	}
                      
                      	public int GetScore(){
                      		return this.Score;
                      	}
                      }

Open in new window


Now there are some other things that you might want to know more about, for example, the 'this' keyword.
Using 'this' inside a class, always refers to the current instance of the class.

Next, one might ask what 'void' is, those who played around a bit in C/C++ might know it already.
Void means that the method does not have a return value.
If you don't get it yet, i will explain this a bit with the following example, where i write a console application and write data to the console:

using System;
                      
                      namespace EETutVoidExample
                      {
                          class player
                          {
                              public string Name;
                              public int Age;
                              private int Score;
                      
                              public void SetScore(int NewScore)
                              {
                                  if (this.Score < NewScore)
                                  {
                                      this.Score = NewScore;
                                  }
                              }
                      
                              public int GetScore()
                              {
                                  return this.Score;
                              }
                          }
                          class Program
                          {
                              static void Main(string[] args)
                              {
                                  player Player1 = new player();
                                  Player1.Name = "Jill";
                                  Player1.Age = 15;
                                  Player1.SetScore(100);
                                  Console.WriteLine(Player1.GetScore());
                                  Console.ReadKey();
                              }
                          }
                      }

Open in new window


Running this code will output:

100

Open in new window


And wait for a keypress to close (Console.ReadKey();).

As you can see in the Console.WriteLine-line, where i write the output to the console, it is output from the GetScore() method.
In the declaration of that method, i said it was a 'public int', so it's remotely accessible, and returns an integer.
In the declaration of the SetScore, i said it was a 'public void', wich says it's remotely accessible, but returns nothing.

The code you see above is a full functioning program. If you played around a bit with C# already, feel free too fiddle around with it.

Next time we will learn to get used to the Visual Studio user interface, creating a new project, saving them, compiling and running them.

For now, if there are any questions, please feel free to ask!
1
4,465 Views

Comments (1)

Commented:
Excellent work, Japy!

I truly appreciate your tutorial, it is very helpful and provides a good reference

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.