Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

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

Initiate Mage
Joined
Nov 24, 2008
Messages
19
Reaction score
15
Introduction
Hi all and welcome to my first tutorial (and 3rd post) on RaGEZONE.
After i did a little for fun, Mental asked me if i could do some tutorials.

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 .
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:

Code:
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
	}
}

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 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:

Code:
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;
	}
}

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:

Code:
using System;

namespace RZTutVoidExample
{
    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();
        }
    }
}

Running this code will output:

Code:
100

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!

Edit:
I'm also posting this series on Experts Exchange.
Also, soon(tm) i will post the follow-up.

Thanks for all the positive comments!
 
Last edited:
Banned
Banned
Joined
Jul 5, 2004
Messages
129
Reaction score
0
Japy, why dont you post our old xna project ?
Guess we wont be working on that one anymore, so maybe a nice example/base for someone else.
 
Initiate Mage
Joined
Nov 24, 2008
Messages
19
Reaction score
15
Japy, why dont you post our old xna project ?
Guess we wont be working on that one anymore, so maybe a nice example/base for someone else.

Yea i'd like to get there later, but first what's first: the basics ;)
 
Banned
Banned
Joined
Jul 5, 2004
Messages
129
Reaction score
0
Yea i'd like to get there later, but first what's first: the basics ;)

Ahh, making steps ?

Maybe a good idea to develop an example project and go further into that by adding new features using larger / little more complicated techniques / functions / classes.

Something like the old Nehe way :lol:
 
Initiate Mage
Joined
Nov 24, 2008
Messages
19
Reaction score
15
Something to add to your tutorial, college students can get Visual Studio 2010 Professional for free at

;)

Nice find! Professional is not really needed for the followers of my tutorial because i try to stick with Express as much as possible, to make it accessible and free for everyone :) but sure is interesting for anyone,
 
Initiate Mage
Joined
Nov 24, 2008
Messages
19
Reaction score
15
Thanks for all the comments :)

Soon(tm) there will be a 2nd part, but i'm really busy for my work and traveling a lot lately.

Two more weeks before my holiday :) but i hope to do it early'er!
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
Superb Object Oriented Programming Tutorial for beginners! Clear up some of the things like setName() (You said it's a bad name- well lead by example with a good name). Also some minor read issues with thelongvariablenameslikethis. Perhaps_underscores_or_at_least camelCaseSoItIsEasierToRead. (I prefer underscores).

But, most importantly, the concepts you're putting out there are clear. That's why I love this tutorial. Looking forward to the next one(s) ;) (Turn them into a book? Not overnight- but it could be a worthwhile hobby for somebody like you.. You have a gift.)
 
Banned
Banned
Joined
Oct 20, 2006
Messages
3,245
Reaction score
1,652
Just a few things I'd like to point out:

  • Use strongly-typed names. ie. class, method, and public field names should always start with an upper-case letter. Private fields should not.
  • You don't have to initialise integer fields in a class' constructor, as they will always have a default value of 0.
  • GetX and SetX methods are for Java and other non-CLR languages. If you're exposing a field in C# and want to do calculations when someone gets/sets the value, use an accessor. eg
    Code:
    int _score;	// I prepend an underscore to identify backingfield members, although you may not want to do this as it's not common
    
    public int Score
    {
    	get { return _score; }
    	set
    	{
    		if (_score < value)
    			_score = value;
    	}	
    }
  • As you can see in the example above, if you only have 1 line after an if clause, you can omit the brackets.
  • Try and keep classes seperated into their own files, especially the main Program class.
  • When waiting for a user to press a key to end an application, it's customary to notify them of this. A simple Console.WriteLine("Press any key to quit..."); will suffice.

@s-p-n: You should always use CamelCase with C#. Underscores are more of a Ruby thing.
OFFTOPIC: Does your name have anything to do with "Supreme Pie Ninja" by any chance?

P.S. The "private" modifier is redundant. All variables and methods are private by default, whereas classes, structs, enums, and interfaces are internal.
 
Last edited:
JavaScript Is Best Script
Joined
Dec 13, 2010
Messages
631
Reaction score
131
I may have posted an extremely late reply, but i think that this will be helpful for some.

Code:
using System;

namespace RZTutVoidExample
{
    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();
        }
    }
}

The above code can be simplified to :

Code:
using System;

namespace RZTutVoidExample
{
    class player
    {
        public string Name;
        public int Age;
        private int score;
        public int Score{ get{ return score; } set { if (score < value) score = value; } }

    }
    class Program
    {
        static void Main(string[] args)
        {
            player Player1 = new player(){ Name = "Jill", Age = 15, Score = 100 };
            Console.WriteLine(Player1.Score);
            Console.ReadKey();
        }
    }
}

and i strongly feel that it should be simplified like this because:
1) Properties in C# are more powerful than Fields in Java (not that Java is bad but...), properties (the get and set) can be implemented to replace explicit getter and setter methods used for fields (e.g. public int GetBalance()) and by doing so you need not spend too much on typing when you wanna get or set the field values, with validation still done. This is illustrated with "Score = 100" : validation still occurs.
2) Properties allows you to do component modelling, which is more than useful and neat for WinForm applications.
 
Back
Top