Overclock.net banner

[FAQ] A Beginners Guide to Programming, C#.

52K views 72 replies 43 participants last post by  xquisit 
#1 ·
Before beginning this is for the absolute beginners. Because we all know at first coding can be a little daunting. Most people (although i picked it up right off the bat) have issues just grasping the basic if statement system. So this is a quick overview to get them started up on that and programming. In this guide i will be using C# (pronounced C Sharp), a very powerful language with a managed environment. Just as fast as C++ with the exception of speed lost due to it being a managed environment but you can get 10 times the work done in the same amount of time (not literally of course but you get the point.) Keywords such as if are colorized, pay attention to these words as i have done this for a reason.

First off, download and install Microsoft Visual Studio 2008 Express Edition C#. This is a free compiler made by Microsoft for C#.Net. Accompanied will be the .Net framework either version 2.0 or 3.5 (pending your OS.) I wouldn't recommend downloading the MSDN Library since its only a small section of information that is rarely used and adds a large amount of time to the setup. Additionally i want to explain the color coating. Light blue is for data types such as strings, integers, or doubles. Blue (regular) is used for statements, such as : if, switch, else. Light green is used for various other things like project names.

Part 1 : Hello World! Applications

If you are using Visual Studio now, heres instructions to create a form with a button to execute our code. Open Visual Studio and click create new project. Then select windows forms application. Once thats done open your toolbox and drag a button onto the form. Right click and click properties if you want do edit anything about the button, such as text. Double click the button to bring up the button click event (an event is a section of code executed when something happens.) To achieve this we call the MessageBox class. And the Show function. For arguments we enter the string "Hello World!" Take note that all strings that are not variables must be enclosed in double quotes ("".)

Code:

Code:
MessageBox.Show("Hello World!");
To begin explaining this Messagebox.Show is a functions. The value inside parenthesis is called an argument. In this case the argument is a string with the value "Hello World!" Put together this code displays a message box with the test "Hello World!" in it and an ok button to close it. (On an advanced note, this function locks the thread it is executed in until the OK button is clicked.) At the end a semicolon ( ; ) is placed, this indicates the end of a line.

Part 2 : Variables, Data Types, && Specifics

Above we used a string as an argument. A string is one of the 13 data types in C#. The most common data types used are : strings, integers (sizes 8 - 64 bits), doubles, decimals, booleans and floats. The following is a list of these, and what types of information they can store.
  1. Strings : Contains Unicode characters.
  2. Integers (32bit) : -2,147,483,647 to +2,147,483,647. Referred to as Int32. No decimal places.
  3. Doubles : â€"5.0x10-324 to +1.7x10308.
  4. Decimals : +1.0x10-28 to +7.9x1028.
  5. Booleans : 0 or 1, False or True.
  6. Floats : â€"1.5x10-45 to +3.4x1038. Referred to as Single.
To give examples, if we wanted to store a message 1 person sent in a messenger client and send it to another person. I would use a string to contain that value. If i wanted to multiply one number by another, i would use 2 integers. If i wanted to multiply a number (with or without a decimal) by another number (with or without a decimal) i would use a floating points (float, decimal, or double. Doubles are preferred as the fastest floating point. I also want to mention floating points comparing to integers are very slow, use with caution and avoid them. See more in optimization.) If i wanted to store whether something was switched on or off i would use a boolean. The following code shows how to initialize and use variables. (Note // denotes a comment, anything to the right of this is not executed as code.)

Code:

Code:
String mystring = "This is the value of the string, mystring is the name of the variable.";
Int32 myint = 378; //This is a 32bit integer
Double mydouble = 378.0001; //This is a double, unlike the integer it can store decimals, it is slower then an integer. It is a member of the floating point family.
Decimal mydecimal = 1000.873; //This is a Decimal
Boolean mybool = False; //This is a boolean, it can be only true or false. It accepts no other value.
Single myfloat = 2008.29; //This is a floating point.

mydouble = 64.3 * myint; 
/*This sets mydouble to 64 times the value of myint. 
In short, mydouble is now equal to 24305.4. 
We used a double because it can store decimal places necessary for this value. 
The / followed by a * surrounding this text is a way to 
comment out text of multiple lines.*/
Continuing from that. If we wanted to say, multiply a number's current value by a number we would use *=. If we wanted to subtract 2 from a variables current value we would use -=. Some others include /= (division), += (addition), and a few others that aren't as important to cover for now. Heres an example of this.

Code:

Code:
Int32 myint; //Initializes the variable, note it was done without setting the variable this time to show you this can be done as well.
myint = 10;
myint *= 10; //Now myint is equal to 100
Part 3 : The Statements - if, switch, and else.

This is where usually people have issues understanding when i try to teach them how to program. I often start here but decided not to for this FAQ. Lets start with if statements. These statements execute code in brackets only if their requirements are true. The following example only executes code if a boolean is equal to true.

Code:

Code:
Boolean mybool = true;
if (mybool == true) //= is used when settings values, == is used when checking values.
{
MessageBox.Show("This message box is showing because the boolean mybool is equal to true, and thus the requirements of this if statement are met.");
}
Additionally, what if we want code to also execute in the event the requirements for the if statement are not met? For this we use an else statement.

Code:

Code:
Boolean mybool = false;
if (mybool == true)
{
MessageBox.Show("mybool is equal to true");
}
else
{
MessageBox.Show("mybool is equal to false");
}
What if the value may have multiple answers, but we wont want to write all those if statements needed? We would use a switch statement. The switch statement changed the code to be executed based on the value of the variable in parenthesis.

Code:

Code:
int32 myint = 2;
switch(myint) //This specifies we are talking about the value myint.
{
case(0) : 
MessageBox.Show("myint is equal to 0");
break;
case(1) : MessageBox.Show("we can also format it this way"); break;
case(2) : MessageBox.Show("this is what will execute since myint is equal to 2"); break;
}
As you saw above, switch is followed by the value the statement is dealing with in parenthesis. And case is followed by a value in parenthesis. If the value the switch statement is referring to is the same as a value inside the parenthesis next to the case statement then the code of that case statement is executed.
 
See less See more
#2 ·
Part 4 : Data Type Conversion, Explicit and Implicit

Often you have the need to have 1 type of data be another type. For example you need to display an integer in a string. To do this you would use an explicit data type conversion. In this example you will see a message box displaying the value of an integer using explicit data type conversion.

Code:

Code:
int myint = 75;
MessageBox.Show("myint = " + Convert.ToString(myint));
Simple enough, even simpler is implicit data type conversion. This doesn't really need conversion at all, you just enter the values into the code as if they were the same data type. This can rarely be used, unless you are dealing with a 32bit and 64bit integers you will need to use explicit conversion instead.

I'm sure you are wondering why you need to do this. To make it simple, the data is stored in the RAM in different formats. Just like jpg images and gif images are saved in different formats. You can't open a gif image in a program that doesn't support it, same as you can't reference a string as a number.

Part 5 : Arrays, Matrices, and More

This is where it gets interesting, an array is basically a list. Using coordinates you can find what data is located in a position on that list. For example lets imagine the array as a series of dots. Each dot contains a value. It would look something like this.



Dot 1 is equal to 10. Dot 2 is equal to 12. And so on. This can be unimaginably useful. For example we have the user tell us a series of muffins 0-8 and each muffin he inputs a string telling us what kind it is. Then in code we enter it into out application. It would look like this.

Code:

Code:
string[] myarray = new string[6];
myarray[0] = "blueberry";
myarray[1] = "plain";
myarray[2] = "raspberry";
myarray[3] = "chocolate";
myarray[4] = "mixed berry";
myarray[5] = "all berries";
string[] specifies we are initializing an array. String declares it will be an array full of strings and [] tells us it is one dimension (this will be explained later.) Then we use an = sign followed by new, new is a keyword that must be used here. Then we declare its size in string[6]. The [6] means it will have 6 coordinates, 0 - 5.

Ok next we will cover Matrices. A matrix is a 2 dimensional array. We have all seen those tables where you have the answer to multiplication questions. You know 1 horizontal coordinate and a vertical one. Using these two coordinates you could find the value of one number times another. This is exactly what a matrix is. For example i will use this diagram, with coordinates marked.



To initialize and use a matrix we code like this :

Code:

Code:
int32[,] mymatrix = new int32[2,2];
mymatrix[0,0] = 0;
mymatrix[0,1] = 0;
mymatrix[0,2] = 0;
mymatrix[0,0] = 0;
mymatrix[1,0] = 0; //Note i didn't set all the coordinates to show you don't have to.
To mark that an array is a matrix we use a coma in the braces. For every coma you add you are adding a dimension. If you used 2 comas for example you could form a 3 dimensional array. Using a matrix you could for example label muffins, and also tell where they were on the cookie sheet by assigning each 2 coordinates based on their number in vertical and horizontal columns of the cookie sheet.

Part 6 : Loops

A loop is a section of code that is repeated until a given value is met. There are a few times of loops out there but we will focus on 2 specifically. For and while. Loops are one of the most useful aspects of programming. They can be used for anything from searching for prime numbers to checking how many friends you have on a list. Lets begin with the while statement. Lets say you want to repeat some code until a value reaches a certain point, and keep track of how many times it took. One way to do this is to use a while statement.

Code:

Code:
int Fnumber = 0;
int Snumber = 2;
while (Snumber < 10)
{
Fnumber += 1;
Snumber += 1;
}
MessageBox.Show("Finished, it took " + Convert.ToString(Fnumber) + "repetitions to make the second number equal to 10.");
Now lets look at the for statement with the same task.

Code:

Code:
for(int i = 0; Snumber < 10; i++)
{
Snumber += 1;
}
MessageBox.Show("Task complete, it took" + Convert.ToString(i) + "repetitions to complete.");
I think this deserves a bit of an explanation. Unlike the while statement for is a bit hard to just up and read without an explanation. The first argument in for is often used to declare a variable used in the loop. This variable is often named i, its kind of like tradition. This code here is ran before the loop, then never again. The next argument (separated by a semicolon) is the requirement for the loop to run, as long as this requirement is met the loop will keep going. If it is not met the loop will cease. The next argument is executed each time the loop runs. This is often used to increase the value of i. This is because unlike what we used here i is often used to set the number of times the loop runs. To demonstrate the more common use heres an example.

Code:

Code:
for(int i = 0; i < 10; i++)
{
MessageBox.Show("Every iteration (cycle, repetition) i is increased by 1 (this is done by ++ which effectively means += 1) until it reaches 10. Since we started at 0 it takes exactly 10 cycles to get there.")
//The above message box is shown 10 times before the loop ends.
}
Part 7 : Threading (Explanation Only)

I want to start out by saying i'm only covering the basics of threading. This is a difficult topic for most people and honestly doesn't belong in a beginner's guide but it is a crucial part of programming i think no one should do without learning for any reason. A thread, to the CPU, is a sequence of code to be executed. Each application by default has a single thread and windows divides up how much time each thread gets on the CPU based on its priority level and how active the CPU is verses the needs of the application. For example if you use two threads, this effectively allows you to split the workload between them and make your program work on 2 cores at once, or 4 threads can use quad cores. Note that it takes up CPU cycles to control threading, so if your not talking about major CPU tasks it may actually sacrifice performance to use multiple threads regardless of how many cores are on the machine. Note i won't be providing how to multi-thread, or manage the main thread. None of that belongs in a beginners guide, probably shouldn't have even mentioned it. At a later time i may write an independent FAQ concerning threads. Until that time this is all i will provide.
 
#3 ·
Part 8 : Knowledge Application

Now that we've covered most of it all, its time to look at an application and use it to further your understanding of the previously studied concepts. We will cover a few basic assignments with full explanation.

The first is how to return the remainder of 2 numbers when divided. The second is use of data type conversions for reasons more then just converting the data type. The third is adding 2 matrices.

Code:

Code:
int 1int = 5;
int 2int = 9;
int 3int;
3int = 2int % 1int;
This returns the remainder of 9 / 5 (4) to the integer 3int. The % operator returns the remainder of the first number divided by the second.

Code:

Code:
Double mydouble = 1.337;
int myinteger = 3;
while (true) //The while statement with the value true as an argument signals an infinite loop, broken only by the break statement.
{
    if (mydouble == myinteger / 3)
    {
        break;
    }
    else
    {
        mydouble = Convert.ToDouble(Convert.ToInt32(mydouble));
    }
}
In this code we removed the decimal places from a floating point by converting to an integer.

Code:

Code:
int position = 0;
int[,] 1matrix = new matrix[2,2];
int[,] 2matrix = new matrix[2,2];
for(int i = 0; i < 3; i++)
{
    for(int o = 0; o < 3; o++)
    {
        1matrix[(i - 1),(o - 1)] += 2matrix[(i - 1),(o - 1)];
    }
}
Pay careful attention to this code, do not proceed until you understand it. I will let you figure it out on your own, i feel it is a crucial part of the learning process.

Part 9 : Optimization

Optimization is a crucial part of programming, especially with loops. Optimization is all about minimizing CPU cycles. For example division is said to take many CPU cycles, this is because as we do the CPU tests each number to see if it can divide a number over and over until it finds the answer. This consumes much power. So 6 / 2 is 3 (3 CPU cycles) times slower approximately then 6 * 0.5 (about 1 cycle.) Division is one of the floating point operations. All floating point operations are very slow and hence you want to avoid them. As i said before floating points themselves are the single, double, and decimal data types. The fastest data type is an integer, so you are going to want to use them whenever possible instead of floating points.

Another point i want to make here is AMD's K8 architecture is heavily geared towards floating points over Intel's architectures. Just an interesting bit of info.

Part 10 : Finishing Touches

Thanks for reading the guide, hope it helps allot of people who want to learn how to program. I spent my entire day on this (
?) and i think i did a decent job, any suggestions for additions or questions post or PM me pending your judgment on which it deserves. Programming is a truly great field to partake in. It is allot of fun and challenging mentally to boot (and sometimes physically, oh the longs nights spent over a hot mouse... then you pass out during the 37th debug run.) Heres some helpful links i use often, enjoy.

http://msdn.microsoft.com/en-us/library/default.aspx

http://www.wikipedia.org/

http://forums.microsoft.com/msdn/default.aspx?siteid=1

http://www.microsoft.com/express/

http://msdn.microsoft.com/en-us/vcsharp/default.aspx
 
#9 ·
Sweet, man... i've been wanting to learn how to program for ages, and this will help loads, esp since i can get the stuff off of Dreamspark...
 
#10 ·
Awesome!
 
#12 ·
I don't like your thinking of arrays at all. You should be using a topological approach to support the understanding of multi-dimensional arrays. I'll start by asking you about: how do you think of 4 dimensional arrays?

And you don't have an answer because you can't... except by thinking of this: variable[2][8][3][7];
Which doesn't help.

So, I highly recommend for new programmers to think of arrays as a tree diagram. Every new dimension is a new split in a tree. Try drawing it out and you'll see you'll be able to draw as many dimensions beyond 3... Sweet. (Now you can go to some bar and bet people there that you can draw something with 10 dimensions...)
 
#14 ·
Quote:

Originally Posted by version2 View Post
I don't like your thinking of arrays at all. You should be using a topological approach to support the understanding of multi-dimensional arrays. I'll start by asking you about: how do you think of 4 dimensional arrays?

And you don't have an answer because you can't... except by thinking of this: variable[2][8][3][7];
Which doesn't help.

So, I highly recommend for new programmers to think of arrays as a tree diagram. Every new dimension is a new split in a tree. Try drawing it out and you'll see you'll be able to draw as many dimensions beyond 3... Sweet. (Now you can go to some bar and bet people there that you can draw something with 10 dimensions...)
My thinking of arrays is to help the user understand the way they can use coordinates. Using a tree for a 2 dimensional array wouldn't totally encompass the understanding of these uses. For example your listing numbers in rows of ten. Every y x's value is increased by 10 because of this (x being horizontal coordinate y being vertical.) On a tree that could look confusing, but imagining it how it is (a plain) will yield instant "ok i understand that, simple" responses.
 
#15 ·
Quote:


Originally Posted by version2
View Post

I don't like your thinking of arrays at all. You should be using a topological approach to support the understanding of multi-dimensional arrays. I'll start by asking you about: how do you think of 4 dimensional arrays?

And you don't have an answer because you can't... except by thinking of this: variable[2][8][3][7];
Which doesn't help.

So, I highly recommend for new programmers to think of arrays as a tree diagram. Every new dimension is a new split in a tree. Try drawing it out and you'll see you'll be able to draw as many dimensions beyond 3... Sweet. (Now you can go to some bar and bet people there that you can draw something with 10 dimensions...)

His way is a good method of beginning to understand multidimensional arrays. It is unfeasible with higher numbers of dimensions, but if you really need to think critically about multidimensional arrays its best to think about how they are layed out in memory (linearly) rather than trying to wade through trees. If you try to do it with trees you run into a different problem - a 10x10x10 array already has 1000 leaves and would be way too dense to actually be a useful visual.
 
#18 ·
Awesome, REP+

from what I see is that C# is a combination of C++ and VB codes right?
 
#20 ·
Quote:

Originally Posted by Licht View Post
No C# is a combination of C++ and Java. Nothing like VB in the slightest if you get into either more then just the up front images.
I saw the messagebox is same as VB and got confused

I didn't try C# yet as the college requires c++, VB and JAVA only
 
This is an older thread, you may not receive a response, and could be reviving an old thread. Please consider creating a new thread.
Top