Вы находитесь на странице: 1из 58

Basic C# Tutorial

PDF File made by Jack023 Credits for all the


C# tutorials are fully to BaussHacker.
Welcome to another C# tutorial by me. This tutorial is
100% written by me on behalf of 143. I will be covering
the same things as I did in my previous tutorials though I
have rewrote a bit, but then I have covered a few new
categories, which you can see. I've chosen to cover the
Windows Forms in this as well! I hope you'll enjoy this
thread and that you will learn something from it!

Regards,
BaussHacker.

Note: As Visual Studio doesn't work for me then I've been


using SharpDevelop for the projects.
It shouldn't do a difference code-wise though, but it might
be a bit different when coming to Windows Forms!
Basic C#
Chapters:

Page 4. C# Introduction

• Page 5. .NET Framework



• Page 6. IDE & Compiler

• Page 7. Your First Project & Application

• Page 14. Data-types & Variables

• Page 19. Strings

Page 21. Booleans

• Page 22. Conditional Statements



• Page 26. Switch

• Page 31. Type-Conversion

• Page 34. Loops #1 (For & While)

• Page 36. Arrays & Collections

• Page 40. Loops #2 (Foreach)

• Page 42. Classes

• Page 45. Access Modifiers

• Page 46. Properties

• Page 48. Methods & Functions

• Page 50. Parameters, Ref & Out

• Page 53. Enums

• Page 55. Generics

Page 56. Exceptions



C# Introduction
Introduction:
In this chapter I will explain a bit about C# and what it is, but also why it's a
great language to learn.

C# is a wonderful language to use. It's very easy to use and you can continue to
other languages after like Java & C++. They won't be that hard to grab if you've
learned C#. I don't see a point in jumping from C# to Java though as they're
both "High Level" languages, but from C# to C/C++ would be a great idea,
because they're both build on the C-syntax. A lot of people who are new to C#
mistakes C# for being in the C-family, but it's not. It has nothing common with
the C-family (C, C++, Objective-C etc.) and the only thing in common is
basically some of the syntax. C# is not unmanaged either which means it does
not compile to assembly, but to the CIL. You can still use C# on other platforms
with the use of things such as Mono etc. I won't be covering other operating
systems than Windows though as I do not have experience with anything else.

So why is C# a good language to learn?


Well it's very easy to pickup and there isn't that much of advanced words to
use. It's basically English everything which is what's a + about the .NET
Framework and its libraries. Even if you come from other languages based on
.NET such as VB.NET then you can still pickup C# easy as you'd basically only
need to learn the syntax. I've heard from people who started out
with VB.NET and then went to C# that they're very happy to do that because
they can do the same and a bit more as well continue much easier to other
languages. Though I've heard a few saying that they had it hardest with coming
from VB.NET to C#, because they had to end everything with a semicolon and
the way that variables are declared is a bit different. If you get a good grab
around that then you should have no problems coming from VB.NET to C#.

So what if you have no programming experience at all, is C# easy to pick up?


Yes. It was the first programming language that I learned and you might struggle a bit in
the start to understand the concept behind programming and remembering keywords
etc. but just give it time and for god's sake don't cheat yourself to say you know more
than you actually do, because you'll only cheat yourself by doing that! Some might learn
it faster than others, but take the time you need and do not compare your learning time
with others. We also learn different, some might learn better from practice while other
learn better from e-books, tutorials or maybe even videos. I do not recommend videos
for programming though and the reason is simple. When you watch a video you can't
really follow what is done that much and you might have to rewatch it over and over to
actually understand or see what's going on. That's why an e-book or tutorials might be
better as you'll get to write code yourself rather than looking someone who codes. You'll
remember what you did much better that way!
.NET Framework
Introduction:
In this chapter I will be explaining a bit about the .NET Framework and what it
is.

The .NET Framework is a huge framework of libraries and other stuff developed
by Microsoft. I will not go in depth about the actual .NET Framework, because
it's a huge area and if you'd like to know more about it then you should check
out Google, but basically as I already mentioned it's a huge library developed by
Microsoft.

Basically most things developed for Windows are in some sort using .NET
Framework this goes from Windows Applications to X-Box Games. .NET is not
necessary to make something work on Windows or any of Mirosofts devices, but
it's a huge help when developing something, because it speeds up your
development, that's why C# has become one of the leading Rapid Development
Languages out there today.

If you compare C# with C++ then C++ might beat C# by performance, but the
time it takes to create something elegant in C++ will take far more time, but its
dependencies is also lower, but even with the dependencies C# is still a great
language and if you wish to continue to learn C++ and more powerful
languages later then C# is perfect, because it teaches you programming in a
good and "fast" way, but also an elegant way of produce your code which you
can use later on.

Enough of that now, but basically when developing something for the .NET
framework the users must have the .NET Framework installed. As of now it's
installed already on Microsofts devices, usually .NET 3.5, but also .NET 2.0.
As of now with VS 2012 they have released 4.5, but a lot of people still prefere
to use 4.0 which I do as well. You can always change your properties of your
application to use a lower .NET Framework, but remember that the lower .NET
you choose, the less features will be available and you might have to code some
things yourself, instead of relying on classes and methods they have already
created. Try to target your project at .NET 3.5 because it's the most common,
but if you must then you can use .NET 4.0. I wouldn't recommend to use 2.0 at
anytime unless you want as less dependencies as possible and you don't mind
doing quite some code yourself.

Downloads/Links:
.NET Framework (Wikipedia) (http://en.wikipedia.org/wiki/.NET_Framework)
CIL (http://en.wikipedia.org/wiki/Common_Intermediate_Language)
C# Express Download (C# Express 2012)(Official Microsoft Website)
Sharp Develop Download (http://www.icsharpcode.net/OpenSource/SD/’
MonoDevelop Download (http://monodevelop.com/)
IDE & Compiler
Introduction:
Before you start you'll need an IDE and a compiler. Luckily Microsoft have
already created that for us when they decided they'd create their language they
already had in mind that the users of their language would need to have some
kind of environment to create their codes on and that's what's called Visual
Studio.

There is a difference on an IDE and a compiler thought and it's important you
understand the difference.

An IDE (Intergrated Development Environment) is an application which you can


use to produce your codes in. Technically you could do them in ex. notepad
(Some actually preferre to use Notepad++) however that will only slow down
your work, because an IDE usually include things such as project creation,
project explore, easy binding to a compiler, syntax high light, auto-indent etc.
Visual Studio already include all that and more. If you're developing C# then
Visual Studio would be the best IDE, but if you have problems with it using too
much CPU or being slow then an alternative IDE could be the SharpDevelop or
Mono (Which is available for Linux, Mac and other OS's as well.) Though Mono
requires the Mono C# compiler and I'll not be teaching anything related to
Mono, so I'd suggest not to look into Mono unless you want to be on your own.

Visual Studio Image:

Source: http://www.otakusoft.com/wp-content/uplo...0/code.png

A compiler is the program that we use to convert (compile) your code into
machine code. In our case we do not compile to native code (machine code or
assmebly if you preferre to say that.), but to the CIL or MSIL. The CIL will then
compile the IL code into machine code at run time. I could be wrong at this as
I've never looked it up that much and it's just from the tip of my tongue I say
this as I felt too lazy to search.

To get started you'll need the IDE and compiler for C#, if you do not have Visual
Studio and do not wish to buy it then you can get the C# Express version which
is free. After 30 days or something you'll have to activate it and you can do that
by signing up and then you'll be send a free key which will activate your product
permanent.
Your First Project & Application
Introduction:
In this chapter you'll be creating your first project in C# as well your first
application. The very basics of a C# programming interface is covered here as
well.

First of all start by starting Visual Studio up and then go to File -> New ->
Project.

I will only cover Console Applications in these tutorials, because that's the best
way to actually learn the language, instead of jumping into Windows Forms and
event handling then you won't have to struggle with it later, so as of now start
out with a Console Application.

I will be calling my application "My First C-Sharp Application". You can call
yours whatever you want, the name doesn't really matter.

At the right side you'll see your solution. A solution can be consiting of more
than one project, but that's not important now as we'll only work with one
project at a time. When you start to use more projects then when you start to
create real applications.

Solution Explorer:

You can view all the files and folders in your project. The .cs files is the C-sharp
Codefiles which is the files you want to code in. If you want to add new files you
can right click your project and choose "Add".

We won't look into this now, so don't sweat it.


At your left you should see something like this:

That is the place you want to produce your code. You might not understand
what these things are now, so let's break it down.

We'll start with the first few lines showed which are the following:

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

The using keyword basically tells that we want to use a namespace. The
"words" you see afterwards ex. System; is the namespace we want to use.
You may want to use one or more namespaces and that's why you can use
multiple namespaces.

The ; (semicolon) is used to finish a statement. If you come from VB then it'll be
hard to be used to use that all the time, because in VB you won't have to use it
at all, but the beauty of using it is that you do not have to have seperate lines of
all your code.

This:

Code:

using System;using System.Collections.Generic;using System.Linq;


using System.Text;
Is actually equal to:

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Now I'm not saying you should do that, because you should still keep in mind
that your code should be readable by yourself and others who's maybe going to
use your code or is your team-partner.

The next thing we see is the keyword namespace.


Basically it will give a sequence of classes, structs and other things a name
which you can use to access them. Basically namespaces are useful to group
your classes, so it's easier to navigate through your classes.

In our case the default namespace is My_First_C_Sharp_Application for me, but


for you it will be whatever your project was called. If you make a new folder
then to create a new namespace (Will use the folder name) then a good idea is
to right click the folder and then add your classes through there, because they'll
be given the default namespace + the folder name as a namespace.

We could use this as a reference:

Code:

System.Linq

System would be our default namespace and Linq would be a folder under the
System project.

Now this is not exactly how it works and it was just an example.

Now we'll see this:

Code:

class Program

I won't really explain a lot about that, because you'll learn about classes later
on, but basically a class is a sequence of variables and methods which you have
to access through that class.
Example on MyMethod:

Code:

class Myclass
{
public static void MyMethod()
{
}
}

Cannot just be accesed like:

Code:

MyMethod();

We would have to do it like:

Code:

Myclass.MyMethod();

And if it was in another namespace we would have to type the namespace as


well or do as the first thing I explain use the using keyword to define the
namespace. Then we wouldn't need to type the namespace, but could just do as
above.

Code:

Mynamespace.Myclass.MyMethod();

The next thing we'll see is this:

Code:

static void Main(string[] args)

That is a method. I won't really explain this what it does, but what I'll explain
here is that the Main method is first default entry point, but it's possible to
actually execute some code before it gets to that using constructors, but I won't
be teaching any of that now as it's not relevant and I do not expect you do
understand it, if you do not have any experience at all, so just remember the
Main method as being the entry point of the application. That's where we want
to do out code for the next tutorials, so do not focus on any of the codes shown
here as of now.

At last there is brackets { & } which you may question yourself what does.
Brackets in C# is used to declare a scope. Basically every scope in C# has some
sort of code. The places where you usually are using scopes would be
namespaces, classes, methods, properties & loops.

And explanation of the scopes for the different types.


Namespace scope:
A scope for a namespace can hold different classes, structs, interfaces,
delegates, enums and such things, but not variables, methods etc.

Class scope:
A class scope can hold variables, properties, delegates, methods, other classes,
interfaces, structs, enums and such things.

Method scope:
A method scope can hold variables, operations (ex. i += 10), loops and codes
for execution. A method cannot hold any other types can variables thought.

Property scope:
A property scope will consist of one or two scopes. A scope for get and a scope
for set. The get has to return a value which is the same type as the property and
the set will basically set the value of the property (Usually linked to another
variable.). The two scopes is actually the same as a method scope. You'll learn
more about this when we get to properties.

Loop scopes:
A loop scope has to be declared within a method scope as it's just looping
through a sequence of codes that are getting executed. That means the loop
scope can hold the same things as a method scope.

Now let's get started with some writing to the console. We have to use the
Console class which is a part of the System namespace, but since we have
already declared the System namespace (As I explained earlier) then we can
just call Console. and we want to call the WriteLine() method, however there is
Write() as well. WriteLine() will write to the console and create a new line
afterwards, which Write() won't. You can try type a string in the parameters.
You start a string by using " and ending it by using " as well.
Ex:

Code:

"Hello Hack Forums!"

You have to do that as the parameter. A parameter is the variables or what you
can say that is passed into a method when called.

Ex.

Code:
static void MyMethod(string parameter1, string parameter2)
{
}

You'd call it like:

Code:

MyMethod("parameter1", "parameter2");

This is how we'd use WriteLine().

Code:

Console.WriteLine("Hello Hack Forums!");

Now I don't really explain where to put this now and it may confuse you, but
remember what I explained about scopes?

Where do you think a code for executions should be placed? ;)

That's correct in the Main Method.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace My_First_C_Sharp_Application
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Hack Forums!);
}
}
}

To build you press F6, you can find your application in your project folder in
either bin\debug or bin\release. However if you wish to build and run you
simply debug by pressing F5. Debugging is a good tool, because if there is any
exceptions thrown (errors) then it will jump into your code and tell you where
the problem is and tell you exactly what the problem is, but you can also set
breakpoints. Breakpoints can be used to check how your program actually
works and you can use it to check when variables change and what their values
are. It's a good thing to check for errors and mistakes.
To set a break point you just click at the left side of your code editor and it will
create a red dot, which marks the breakpoint. You can click on that to remove it
again as well.

Your program will pause/stop when it reaches that break point and then you
can follow your code line by line. You can have more than one break point.

To follow your program you'll have to press F10 for each line. If you have
finished checking a breakpoint you can press F5 and it will either run the
program regular (If there is no more breakpoints) or jump to the next break
point.

Now try to debug.

What happened? The program closed.

That's weird, isn't it?


Not really, because the program has no more code to execute. We can stop it
from doing that by creating an infinite loop or just call the read methods from
the console class and wait for an input.

ReadKey() will wait for a key input, where ReadLine() will wait for enter to be
pressed. ReadLine() can also be used to give a string a value, because it returns
a string.

Code:

Console.ReadLine();

Final code:

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace My_First_C_Sharp_Application
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Hack Forums!");
Console.ReadLine();
}
}
}

Congratulations you have made your first C# application.


Data-types & Variables
Introduction:
In this chapter we'll be looking at data-types in C# as well variables and how to
declare them.

Now let's take a look at the different datatypes and a first look at variables.
We'll look more into this later.

Data-tpe chart:

Source: http://www.dotnet-guide.com/images/unifi...-sharp.jpg

You may notice that string is not on the list, but maybe I know why that is. A
string is not an actual data type (It is one, but not a simple datatype), but an
array or sequence of unicode characters. Which the char data-type is equal to.
A char is actually equal to a byte as well, but more about that later when we get
to some of the advanced things.

If you look at the example that's how you declare the different variables.
So let's try to declare a string.

Code:

string myString = "Hello Hack Forums!";

Let's break this line into pieces.


The first thing we see is:

Code:

string

That is the datatype of our variable.

Then we have:

Code:

myString

That is the name of our variable.

Then we have:

Code:

That is an operator used to make it equal to the value we're giving it. It can also
be used to assign the left handed variable with a (data)type or pointer.

Then we have:

Code:

"Hello Hack Forums!"

That is the value of our string. A string has to be declared in apostrophes ("),
but an integer ex. int or byte does not need them, but they're also only
numerics as they're integers.

At last we have:

Code:

;
If you cannot remember what it does then read back in the previous tutorial.

Or mark below:
<from>A semi-colon (;) is used as an end statement in C#. For a clear
explanation look back in the previous tutorial.<to>

What I will suggest now is to try to declare different types of variables, look at
the chart for examples.

Now try to see if you can write them out to the console as well.

Example:

Code:

static void Main(string[] args)


{
string myString = "Hello Hack Forums!";
int myInt = 105000;
short myShort = 5252;
byte myByte = 200;
Console.WriteLine(myString);
Console.WriteLine(myInt);
Console.WriteLine(myShort);
Console.WriteLine(myByte);
Console.ReadLine();
}

Now let's look into some mathematical operations.


You can add/remove values etc. to a variable, some variables support other
operators than others, but let's just take a look at int as of now. More about
type-conversion later.)

Here are some examples of mathematical operations:

Code:

int X = 10;
int Y = 15;
int Res = X + Y;

Code:

int X = 10;
int Y = 15;
int Res = X - Y;

Code:

int X = 10;
int Y = 15;
int Res = X * Y;
Code:

int X = 10;
int Y = 15;
int Res = X / Y;

Code:

int X = 10;
int Y = 15;
int Res = X ^ Y;

You can also do this if you wish to make X equal to the result then instead
doing:

Code:

X = Res;

You could just do this from the start.

Code:

int X = 10;
int Y = 15;
X += Y;

Code:

int X = 10;
int Y = 15;
X -= Y;

Code:

int X = 10;
int Y = 15;
X *= Y;

Code:

int X = 10;
int Y = 15;
X /= Y;

Code:

int X = 10;
int Y = 15;
X ^= Y;
These are just examples and there is a lot more operators etc. and things you
can do.

Now let's get more specific what a variable is. A variable is a place in your
computers memory that you can use to hold some data. See your memory as a
city. A city has a lot of different house. The different house has differerent
peoples living/objects stored in them.

If the memory is the city, the variable is the house and the data is the people
and objects in the house.

Example of memory.

That was a bit about data-types and variables.

.
Strings
Introduction:
In this chapter we'll be looking at strings and what they are as well how to use
them.

As I said previous a string is not really a data-type (It is one, but not simple)
and that's why it wasn't on the chart. A string is basically an array or sequence
of unicode characters (char).
The string class contains a lot of useful things and every type in C# can be
converted to string that's why the ToString() method was implemented for all
types, because they're derrived from the System.Object, but the ToString()
method might not necessary return the object as string if it's override to do
otherwise.
You've already been taught how to declare a string and use it, but now we'll
look into string replacement, substring and other things.

Let's start out with the Replace.


The Replace() method takes 2 parameters. Either 2 chararacters (char) or two
strings (string). What this does is replacing a specific sequence of chars in a
string with something else.

An example:

Code:

string myString = "Hello Hack Forums!";


myString = myString.Replace("Hack Forums", "BaussHacker");

The code above will replace Hack Forums with BaussHacker.Now for the
SubString() which can "crop" a specific sequence of strings from the string. You
can either start from an index in the string (Notice everything is 0 indexed in C#
(Almost) same goes for arrays when we get there.) or you can choose to start
from an index and then a specific length.

Example #1:

Code:

string myString = "Hello Hack Forums!";


myString = myString.Substring(6);

The code above will remove Hello and the first space from myString, which will
leave us with Hack Forums!
Example #2:

Code:

string myString = "Hello Hack Forums!";


myString = myString.Substring(0, 5);
The code above will remove the first space and Hack Forums! from myString,
which will leave us with Hello.
Now let's look into adding a string with another string.
The += operator which we have already used earlier can be used to do this
operation, however if doing this a lot I'd suggest using a StringBuilder (Will
show this as well.) The reason is that everytime you use the + operator it
creates a new string for every instance.

An example:

Code:

string myString = "Hello ";


string myString2 = "Hack Forums!";
myString += myString2;

This is how you'd use a StringBuilder.


First you'll have to declare the StringBuilder which is a class.
The new keyword basically means that you creates a new instance. To add a
string we'll have to call the Append() method within our StringBuilder and then
in the end we can just call ToString() to make it a string. Remember to return
the value to a string that has to hold the StringBuilders value.

Code:

StringBuilder stringBuilder = new StringBuilder();


stringBuilder.Append(myString);
stringBuilder.Append(myString2);
string result = stringBuilder.ToString();

Since the Append() method returns the StringBuilder we won't need to write
"stringBuilder" every time we wants to use it, but we can just do something
like:

Code:

StringBuilder stringBuilder = new StringBuilder();


stringBuilder
.Append(myString)
.Append(myString2);
string result = stringBuilder.ToString();

That was a bit about strings!


Booleans
Introduction:
In this chapter we'll just look at the first thing of booleans. More in conditional
statements.

A bool is a data-type that can either be true or false. Every conditional


statement ex. if statement consists of a boolean value.

That means you're using a bool to check if something is true or false.

En example could be:

Code:

bool hasWrite = false; // we haven't written to the console yet, so it's false
Console.WriteLine(hasWrite); // we're writing to the console
hasWrite = true; // we have wrote to the console, so it's true
Console.WriteLine(hasWrite); // we're writing to the console again

I don't think there is much more to explain about booleans before we get to
conditional statements.
Conditional Statements
Introduction:
In this chapter we will be looking at conditional statements such as if, else etc.

A conditional statement is basically a boolean statement. An if statement is a


conditional statement and it basically checks if something is true or not and
then you can create a scope around some code which will be executed if it's
true.

You can also use an "else if" to check if something else is true or false, if the if
statement wasn't executed.

At last there is the else statement which will execute if none of above was
executed. The else can also be used after a single if statement, the else if nor
the else is necessary at all.

Let's try to create a few variables.

Code:

int Age = 16; // the age of the person


int LegalAge = 18; // the legal age to buy beer
int Money = 100; // the money the person got
int BuyCount = 10; // the amount of beers to buy
int BeersInShop = 5; // the amount of beers in the shop
int Price = 8; // the price of each beer

Another way this could be written is:

Code:

int Age = 16,


LegalAge = 18,
Money = 100,
BuyCount = 10,
BeersInShop = 5,
Price = 8;

Now let's say we want to check if the person who wants to buy beers in the
shop is old enough, otherwise it should tell him he isn't old enough.
Code:

if (Age >= LegalAge)


{
}
else
{
Console.WriteLine("You aren't old enough.");
}

Now we want to check if there is enough beer.

Code:

if (BeersInShop >= BuyCount)


{
}
else
{
Console.WriteLine("There isn't enough beer.");
}

Now we want to check if the person has enough money.


For this we need to calculate a total price.
The total price is calculated by the price multiplied with the amount.

If there is enough money it should remove the money and then give the beers.

Code:

int TotalPrice = Price * BuyCount;

if (Money >= TotalPrice)


{
Money -= TotalPrice;
Console.WriteLine("You have got your beers.");
}
else
{
Console.WriteLine("You need more money!");
}
Final code (If you can't figure out.)

Code:

static void Main(string[] args)


{
int Age = 16,
LegalAge = 18,
Money = 100,
BuyCount = 10,
BeersInShop = 5,
Price = 8;

if (Age >= LegalAge)


{
if (BeersInShop >= BuyCount)
{
int TotalPrice = Price * BuyCount;

if (Money >= TotalPrice)


{
Money -= TotalPrice;
Console.WriteLine("You have got your beers.");
}
else
{
Console.WriteLine("You need more money!");
}
}
else
{
Console.WriteLine("There isn't enough beer.");
}
}
else
{
Console.WriteLine("You aren't old enough.");
}

Console.ReadLine();
}

What you should do now is play a little around with the values in the variables
and maybe try to break point to see how everything works. It's a good practice.
You could also try to implement more variables and checks to practice even
more!!

Now let's look into booleans and conditional statements.


You can give a boolean the value of a conditional statement as well.
If you use the example above with the first check then it could also look like
this:

Code:

bool canBuy = Age >= LegalAge;

if (canBuy) // or canBuy = true


{

Note:
I will not suggest the above for if statements, but rather if you actually
need to use a boolean in another scope to check with or something like
that, but not for a single use if statement.

Another thing for booleans is the ! operator which means false. There is also the
!= operator which means not equal.
Switch
Introduction:
In this chapter we will be looking at switches. A switch is a bit close to if
statements, but there is a little difference.

The switch statement is a bit different from the if statement. A switch is faster
in scenarios where you have a lot of if statements. The reason is that a switch
does not go in and check every case (scope) if it's there it should go, but it
points directly to the case it should.

You can compare an if statement with a switch like this.

So when do you use what and why? Well a conditional statement (if) can be
used check various statements like if something is above or something is below,
something is not equal etc. A switch has to have constant values which means
you cannot do checks within the switch.

Let me give you two examples where you want to use if in the first, but switch
in the next.

You want to use if in the following code, however the result is the same.

If:

Code:

int amount = 10;


int reqAmount = 5;
if (amount >= reqAmount)
{
Console.WriteLine("Enough.");
}
else
{
Console.WriteLine("Not Enough.");
}

Switch:

Code:

int amount = 10;


int reqAmount = 5;
switch ((amount >= reqAmount))
{
case true:
{
Console.WriteLine("Enough.");
break;
}

case false:
{
Console.WriteLine("Not Enough.");
break;
}
}
You want to use switch in the following code, however the result is the same.

Code:

Console.Write("Enter a word: ");


string word = Console.ReadLine();

if (word == "abc")
{
Console.WriteLine("{0}defghijklmnopqrstuvwxyz.", word);
}
else if (word == "hello")
{
Console.WriteLine("{0} Hack Forums!", word);
}
else if (word == "omfg")
{
Console.WriteLine("{0} you are nice.", word);
}
else if (word == "hackforums")
{
Console.WriteLine("{0} is awesome!", word);
}
else
{
Console.WriteLine("You entered: {0}.", word);
}
Code:

Console.Write("Enter a word: ");


string word = Console.ReadLine();
switch (word)
{
case "abc":
{
Console.WriteLine("{0}defghijklmnopqrstuvwxyz.", word);
break;
}
case "hello":
{
Console.WriteLine("{0} Hack Forums!", word);
break;
}
case "omfg":
{
Console.WriteLine("{0} you are nice.", word);
break;
}
case "hackforums":
{
Console.WriteLine("{0} is awesome!", word);
break;
}
default:
{
Console.WriteLine("You entered: {0}.", word);
break;
}
}

A switch is build up by cases as you can see. Each case represents a scope and a
case requires you to break it, otherwise the compiler won't allow you compile,
because the case might fall into the next case. The default keyword can be used
for a default case, it's kinda equal to else, because it will go to the default case
if the case of the statement wasn't existing.)
A case can also have more than one identifier.
Example:

Code:

switch (number)
{
case 0:
case 1:
case 2:
case 3:
{
Console.WriteLine("You wrote 0,1, 2 or 3.");
break;
}

case 4:
case 5:
{
Console.WriteLine("You wrote 4 or 5.");
break;
}

default:
{
Console.WriteLine("You wrote {0}.", number);
break;
}
}

I think that's it for now. Try play a little with switches and if statements now!
Type-Conversion
Introduction:
In this chapter we will be looking at type conversion, as well parsing strings to
integers etc.

Type conversion is useful if you want to convert one type to another. Let's say
we have an int, but we want to make it a byte then we'd need to convert it. It
can be annoying that you always need to convert types when working with
calculations and algorithms, but oh well it's for our own safety, because a
wrong conversion can give weird values.

There is different ways of converting one type to another.

The ways we'll be looking into is the following:

Code:

Explicit Conversion
Parsing

The explicit conversion requires us to specify the type we want to convert to.
There is some types that can do it implicit as well which means you won't have
to specify the type, because it can figure it out itself.

This would give an error:

Code:

int myInt = 100;


byte myByte = myInt;

That's an example where we would need to convert.


To do this we'd have to do the following:

Code:

int myInt = 100;


byte myByte = (byte)myInt;

It will no longer give an error.

One thing you should think about when doing type-conversion is the value of
the 2 types. Because not all data types has the same min/max value and it can
cause conflicts and weird values when converting!

If you're interested in getting the MinValue & MaxValue then you can just call
them within the type, because they're constant variables.
Example:

Code:

ulong maxValue = ulong.MaxValue; // gets ulong max


short minValue = short.MinValue; // gets short min

Also another thing is you should now that signed integers can be negative, but
unsigned integers cannot have any negative values.

Signed integers:

Code:

sbyte
short
int
long

Unsigned integers:

Code:

byte
ushort
uint
ulong

Not every type can be used to convert to each other. You cannot convert a
string to an integer explicit nor implicit. You'd have to parse the string value
into an int.

There is two ways we'll look into doing this. Parse and TryParse.
The difference is that Parse will throw an error if the input is not numeric, but
TryParse will spit out a 0 based value if the input wasn't numeric.

Parse: (Correct)

Code:

string myString = "10520";


int myInt = int.Parse(myString);

Parse: (Wrong) - Throwing error

Code:

string myString = "abc";


int myInt = int.Parse(myString);
TryParse: (Correct)

Code:

string myString = "5551212";


int value;
int.TryParse(myString, out value);

TryParse: (Wrong) - Value will be 0

Code:

string myString = "abcacw";


int value;
int.TryParse(myString, out value);

You can also use TryParse as a conditional statement, because the method
TryParse returns a boolean.

Also you may question the out keyword within the TryParse, but as of now think
of it as spitting a value out as a parameter, rather than parsing it as a
parameter, but you'll learn more about that later.

There is also the Convert class which contains methods for converting to
different types as well.

I think that's it for now.


Loops #1 (For & While)
Introduction:
In this chapter we'll take a look at for loops and while loops. Basically a loop is
used to execute some code a specific amount of time.

Now let's look a bit on looping. This is the first part of looping where we'll look
at for loops and while loops. However there will be more about these two things
later.

The for loop and the while loop is a close to each other, however you'll see the
difference on them.

We'll start by taking the for loop.

The "for" keyword is used for that and it takes some arguments.
First argument is an initializer, the second argument is a conditional statement
and the last is an iterator. The loop will run until the conditional statement is
false.

The following code:

Code:

for (int i = 0; i < 10; i++)

Tells us that the variable i is 0 and the loop should run while i is below 10. i++
means that we adds 1 to i. That iterator is called every time the loop has ran
one instance. You can try to debug and breakpoint to check how the loop
exactly works ;).

You have to create a scope for the code in your loop.

Code:

for (int i = 0; i < 10; i++)


{
// do something here
}

About the scope is not entirely true, because you don't need to create a scope if
you only do one statement, but I'll suggest using brackets anyways, because
the code looks better (In some cases.)

Try to do something in the loop and try to explore it a bit, maybe try multiple
loops in each other? :p

Anyways that's the for loop. Let's take a look at the while loop. There is two
ways to make the while loop.
The first way is the most used while loop, which has a conditional statement
first and then does something.

Code:

while (true)
{
// do something
}

The code above will run the loop while true is true, so that's basically an infinite
loop, but you could also do it while some bool is true or an int is below or
something. As it is a conditional statement it takes.

Code:

bool myBool = true;


while (myBool)
{
string s = Console.ReadLine();
if (s == "quit")
myBool = false;
}

The code above will keep ask for an input from the console and if the input is
"quit" then myBool will be false which will lead to the loop ending.

There is another way to use a while loop as well, which is the do-while loop.
You specify a do scope of codes and then the conditional statement after.

Example:

Code:

do
{
// do something
}
while (true);

It will first execute the do scope and then it will check if it should run it again.
The regular while loop will check before it runs the first instance.

That was the first part about loops.


Arrays & Collections
Introduction:
In this chapter we'll be looking at arrays and different types of collections such
as dictionaries and lists.

Now let's look at collections and arrays. An array is also a form of a collection,
but when I mean collection I'm talking about the generic collections such as
List and Dictionary.

First of all let's look at an array. An array is basically a collection of a specific


object, however the size of the array is not expandable. When you create the
array it has to have a specific size.

You declare an array by putting [] after the type and you'll always have to
create a new instance of an array and when you do that you'll also have to put
[] after, however you have to specify a size of the array.

Code:
int[] myIntArray = new int[10]; // the size is 10

Now it's important to understand the index doesn't go from 1- 10, but from 0 -
9, because arrays are 0 indexed.

To add a value we'll have to specify the index that we want our value to be
stored at.

Example:

Code:

myIntArray[4] = 10;

The same thing goes about getting a value.

Example:

Code:

int myInt = myIntArray[4];


You can also specify fixed values in the array and then the array doesn't need a
specific size.

Example:

Code:

int[] myIntArray = new int[]


{
10, // index 0
15, // index 1
1000 // index 2
}; // length = 3

For loops are good to use with arrays, because array items is accessed by an
index and usually a for loop is by an integer value.

Example:

Code:

int[] myIntArray = new int[10];

for (int i = 0; i < myIntArray.Length; i++)


{
myIntArray[i] = i * 10;
}

That was a bit about arrays. Now let's look at generic lists. There will be more
about generics later, but basically when something is generic it means you can
specify a generic type for the object.

List<T> is a class and for that reason we'll need to create a new instance of it.
Let's make a list of ints.

Code:

List<int> myIntList = new List<int>();

To add an int to the list we just call the Add method which will take an int as a
parameter, because we have specified an int to be the type.

Code:

for (int i = 0; i < 10; i++)


{
myIntList.Add(i);
}
To remove an int we'll just have to call the Remove method which will take an
int as parameter as well.

Code:

myIntList.Remove(6); // will remove 6 from the list.

You can also access list values with index like arrays, but the index may not be
the same as the value, depending on type etc. and so on.
That was a bit about list.

Now let's take a look at dictionaries. A dictionary is also a generic collection. It


requires 2 generic types thought. A generic type for the key and a generic type
for the value.

Basically a dictionary works like this:

To access a value you'll need to use the correct key. You can see the keys as the
index (if comparing to arrays.), however the key does not have to be numeric
and it doesn't need to go like 1, 2, 3, 4.

Let's create a dictionary that has a string as key and an int as value.

Code:

Dictionary<string, int> myDictionary = new Dictionary<string, int>();


The dictionary class contains methods for Add and Remove as well. The add
method requires a value as the key and a value as the "value".

Code:

myDictionary.Add("Hello", 10000);
myDictionary.Add("Hack Forums", 50000);
myDictionary.Remove("Hello"); // removes Hello again

To access a value in the dictionary you'll have to use the key it has.

Example:

Code:

int myInt = myDictionary["Hack Forums"];

The code above will get the value from the key "Hack Forums" which in our case
50000.

That was it for now, however we'll look at foreach loops now where we'll return
to dictionaries and how to loop them.
Loops #2 (Foreach)
Introduction:
In this chapter we will be looking at the last type of looping which is foreach.

Now let's look at the last part of loops which is the foreach loop. The foreach
loop can let us loop through ex. a collection. It will take 2 arguments a variable
as the value in the collection and then the collection it should take the value
from.

Let's start out by looping through an array.

Code:

int[] myIntArray = new int[]


{
10,
55,
244,
12421,
6631431,
886125
};

foreach (int myInt in myIntArray)


{
Console.WriteLine(myInt);
}

The code above creates our array and then it simply loops through every value
in myIntArray and prints it out to the console.

The same thing would be for lists. You loop directly through the values in a list
as well, but when it comes to dictionaries you can't. You'll have to either loop
through both the key and value using KeyValuePair<keytype, valuetype>,
through the keys only or through the values only.
I will give an example on all of them.

KeyValuePair example:

Code:

Dictionary<string, int> myDictionary = new Dictionary<string, int>();

myDictionary.Add("Hello", 41521);
myDictionary.Add("Hack Forums", 5121251);

foreach (KeyValuePair<string, int> myPair in myDictionary)


{
Console.WriteLine(myPair.Key); // writes the key out
Console.WriteLine(myPair.Value); // writes the value out
}

Key example:

Code:

foreach (string myKey in myDictionary.Keys)


{
Console.WriteLine(myKey); // writes the key out
}

Value example:

Code:

foreach (int myValue in myDictionary.Values)


{
Console.WriteLine(myValue); // writes the value out
}

That was the foreach loop. I don't think there is much more to explain about it
for now.
Classes
Introduction:
Introduction here

Now the exciding part of learning the C# basics come. OOP (Object Oriented
Programming.)

Now we won't focus so much on code executions, but merely the design of a
proper program and classes.

To create a class we'll use the class keyword which you may already have
learned by now, but if you haven't I'll explain it anyways.

First we'll write the class keyword and then give it a name. After that we'll have
to give the class a scope.

Let's try to make a class called Person.

Code:

class Person
{
}

The class should have 2 variables for age and name.


Now let's think about what type they should be. An age is numeric, so we'd
have to use an integer, but what type of integer would be best?

If we see the person as a human then a byte would be just fine, because there
is no human above the age of 255 (Byte's max value.)

However int is the default integer type in C#.

The name should of course be a string, because it's a "word" and consists of
alphabetic characters.

Both variables has to be declared as public or we won't be able to use them


outside the class and we want to do that, because we want to set/get an age
and same for the name.

Code:
class Person
{
public byte Age;
public string Name;
}
By now you should already now how to declare a new instance of a class as we
have done it a few times by now.

If you can't remember you could look back or look here.

Code:

Person myPerson = new Person();

myPerson.[any member of myPerson]

Example:

Code:

myPerson.Age = 10;
myPerson.Name = "Bob";

What you could do to practice this is to do following:

Code:

-Create a few instances of Person and give them all different values.
-Add the persons to a collection (Array,List or Dictionary etc.)
-Loop through the collection
-Print out the persons data.

The last thing we'll look into about classes is inheritance. A class can inherit
another class as its base.

If we make a new class can call it Girl and another class and call it Boy.

To inherit another class you have to put a colon (:) after the name of the class
and then specify which class you want to inherit.

Both our boy and girl class should inherit the Person class, so let's do that.

Code:

class Girl : Person


{
}

class Boy : Person


{
}
Now we need to make something different about them.
If make a bool if there is Boobs or not then the boy should have false and the
girl should have true.

Code:

class Girl : Person


{
public bool HasBoobs = true;
}

class Boy : Person


{
public bool HasBoobs = false;
}

Now let's try make two new instances of these two persons.

Code:

Girl girl = new Girl();


girl.Age = 16;
girl.Name = "Sarah";

Boy boy = new Boy();


boy.Age = 18;
boy.Name = "Bob";

Now what we can do is write to the console if a person has boobs or not.

Code:

Console.WriteLine("Does {0} has boobs, true or false? {1}.", girl.Name,


girl.HasBoobs);
Console.WriteLine("Does {0} has boobs, true or false? {1}.", boy.Name,
boy.HasBoobs);

That's it for now!


Access Modifiers
Introduction:
In this chapter you'll learn about access modifiers.

Access Modifiers is the kind of modifier an object or a variable has.


There is different kind of modifiers such as public, private etc.

Here is a chart of the modifiers:

Then there is the static access modifier. A static field does not require a new
instance meaning if you create a static field in a class you won't need to create
a new instance of the class and you can just access it directly through it,
however static fields can also have access modifiers for public, private,
protected and internal.

I don't think here is much more to explain about this, other than try to explore
it yourself!
Properties
Introduction:
In this chapter we'll be looking at properties and the get/set keywords.

A property is a variable that can either have a get/set scope or both of them.

They're useful in some cases where you want to do something when a variable
has to return its value or gets a new value.

A property usually consists of two variables. The property itself and then a
variable to store the value.

The name of the variable to store is usually the same name as the actual
property variable, but with the private modifier, in lower case and with an
underscore (_) in front of its name. You can call it whatever you want, the
reason why has something to do with coding standards though.

This is a plain int property.

Code:

private int _int;


public int Int
{
get
{
return _int;
}
set
{
_int = value;
}
}

You should still remember what you can do in the scope of a property, but if you
can't then you should read back as I explained it back in the first project part.

What's good about this is that we can actually check the value that's tried to be
given to the variable.

We could ex. make sure the value never gets above a specific value and if it is
then it should just remain the same.

We'd do that in the set scope.


The difference on the two scope is that the get scope will get the value and
return it, but you can also return something else, it's all up to you what you
return as long the datatype is the same, but usually you'll just return the
regular variable, actually do that always. The set scope however is where the
value will be set. value is a keyword which is the actual value that the was cast
to the property.

Code:

set
{
if (value > 50000)
return; // making sure it won't continue

_int = value;
}

The code above makes sure that the value will never be above 50000. If the
value gets above 50000 it will just return (Since there is nothing to return we
do not give it any return value.) and it will stop it from actually setting the
value to the variable.
Methods & Functions
Introduction:
In this chapter we'll be looking at methods and functions. This will include stuff
like how to call a method as well creating one.

Now we'll look into methods and methods returning a value.

A method is basically a scope of code to execute. If a method is given another


type than void then it has to return a value as that type.

When you declare a method you declares the access modifier, the type and then
the name. You finishes a method with (). Within those youll have your
parameters. We'll look into parameters later though.

Let's try make a static method.

Code:

public static void MyMethod()


{
}

Within the scope you can put codes to execute. You should know by now how to
do that and if you don't then well you should read back to the first thing we
looked at, exactly. The main method.

So try to do some code in that method.

Code:

public static void MyMethod()


{
Console.WriteLine("MyMethod has been executed.");
}

Now since I've placed mine in the same class as my main method then I can
just call the name of the method without specifying the class, but if it was in
another class or wasn't static I'd have to either call that class before the
method name or the instance of the class.

Code:

static void Main(string[] args)


{
MyMethod();
Console.ReadLine();
}
Now what about methods returning something?
Instead of void we can give the method a type. The returning value has to be
the same type as the method is.

Let's change MyMethod to an int.

Code:

public static int MyMethod()


{
}

This will give an error, because we aren't returning any value.


let's ask for an input to a number and return that.

Code:

public static int MyMethod()


{
int number = int.Parse(Console.ReadLine());
return number;
}

Now what we can do is make a variable equal to our method and it will execute
the method and make the variable equal to the return value.

Code:

static void Main(string[] args)


{
int myint = MyMethod();
Console.WriteLine("You wrote: {0}.", myint);
Console.ReadLine();
}

That's it for now.


Parameters, Ref & Out
Introduction:
In this chapter we'll be looking at parameters of methods as well reference
parameters and out parameters.

Now let's look at parameters and the ref and out keyword used with
parameters.

First of all a method can contain multiple parameters or none parameters.


You've learned how to create a method with no parameters as of now, but now
it's time for some parameters.

A parameter is an argument (variable) passed to a method.


You can then use it within the method, but not outside!

Try to make a parameter and do something with it in the method.

What I will do is pass a string and print to the console what was passed.

Code:

public static void MyMethod(string myParam)


{
Console.WriteLine("{0} was passed to MyMethod.", myParam);
}

You should know by now how to pass a parameter to a method, but if you're in
doubt:

Code:

static void Main(string[] args)


{

Console.Write("Enter something: ");


MyMethod(Console.ReadLine());
Console.ReadLine();
}

Now let's look at the ref parameter first. When you pass a normal parameter
then it basically copies the parameter (unless you pass a variable like a class
etc.) If you use the ref keyword it will not create a new instance with the same
type and value, but it will referre to the variable passed as an argument.
Try to change the variable you pass first without using the ref and then write
both values out.

Code:

static void Main(string[] args)


{

Console.Write("Enter something: ");


string value = Console.ReadLine();
MyMethod(value);
Console.WriteLine("value is now: {0}.", value);
Console.ReadLine();
}

public static void MyMethod(string myParam)


{
myParam = "Hack";
Console.WriteLine("{0} was passed to MyMethod.", myParam);
}

Now if we make the parameter a ref parameter then it will actually change
value.

Code:

static void Main(string[] args)


{

Console.Write("Enter something: ");


string value = Console.ReadLine();
MyMethod(ref value); // referring to value
Console.WriteLine("value is now: {0}.", value);
Console.ReadLine();
}

public static void MyMethod(ref string myParam) // tells it that it's a ref
parameter
{
myParam = "Hack";
Console.WriteLine("{0} was passed to MyMethod.", myParam);
}

Now let's look into an out parameter. An out parameter is a bit different from a
ref parameter. The out parameter does not pass the variable it referres to, but it
creates a new variable which it will make the passed variable equal to, so
basically what it does is that it spits out a value. The out parameter can be
referred to something similar as the return value, because it has to be set
within the method.
Code:

static void Main(string[] args)


{
string value;
MyMethod(out value); // tells it that it should spit the value out to "value"
Console.WriteLine("value is now: {0}.", value);
Console.ReadLine();
}

public static void MyMethod(out string myParam) // tells it that it's an out
parameter
{
Console.Write("Write something: ");
myParam = Console.ReadLine();
}

That was it about parameters.


Enums
Introduction:
In this chapter we'll be looking at enums.

Now let's look at enums or enumerators. An enum is basically a scope of names


which can either have a value or not. The value has to be numeric thought. You
can even give your enum a specific type.
An example of an enum could be: (Using HF as reference)

Code:

public enum UserRank


{
Regular,
L33t,
Ub3r,
Mentor,
Staff,
Admin,
Banned
}

An enum can be declared within a namespace or a class/struct.

You'll have to use the enum as a variable though.


Let's try make a new class and call it User and then gives it the previous enum
as a variable.

Code:

public class User


{
public UserRank Rank = UserRank.Regular; // the default rank is Regular
}
Now try create a few instances of it and try to print out their rank.

Code:

static void Main(string[] args)


{
User user1 = new User();
user1.Rank = UserRank.Admin;

User user2 = new User();


user2.Rank = UserRank.L33t;

User user3 = new User();


user3.Rank = UserRank.Ub3r;

Console.WriteLine("user1 was: {0}.", user1.Rank);


Console.WriteLine("user1 was: {0}.", user2.Rank);
Console.WriteLine("user1 was: {0}.", user3.Rank);

Console.ReadLine();
}

I usually use enums within a switch, because it's an easy way to identify each
case (Depending on what you're switching though.)

Now you've learned how to use enums ;).


Generics
Introduction:
In this tutorial we'll be looking at generic types as well generic class usage.

Generic types is the possibility of specifying a type of an object.

We'll try to make our own generic class and you may see that it's similar to List
or Dictionary the way it's used. We're not making a collection though!

First of all create a new class.

Code:

public class MyGenericClass


{
}

Now after the name of the class we'll put < and > to specify that it's generic.
We'll have to give the generic type a name though. It's usually T or TItem etc.

Code:

public class MyGenericClass<T>


{
}

Now we can use T as a datatype for a variable.

Code:

public T GenericValue;

Now try to create a new instance of the class and give it a type.

Code:

MyGenericClass<int> myGeneric = new MyGenericClass<int>();

Notice that when you try to access the GenericValue variable it will have the
same type as the type we chose to use.

Code:

myGeneric.GenericValue = 50000;

There isn't much more that I will explain about generics.


Exceptions
Introduction:
In this chapter we'll be looking at exceptions. This is the last chapter of the
basics and then we'll start to look at a bit more advanced things.

Exceptions are errors thrown by the application. You can handle those errors
though and it's a good thing that the application tells us when something is
wrong because if it didn't then how should we know there was something
wrong? The best thing is that it tells us exactly what is wrong and how to fix it
as well.

Example on an exception:

Code:

System.FormatException: Inputstrengen var ikke i et korrekt format.


ved System.Number.StringToNumber(String str, NumberStyles options,
NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
ved System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo
info)
ved System.Int32.Parse(String s)
ved Exceptions.Program.Main(String[] args) i
c:\Users\Cutecore\Documents\SharpDevelop
Projects\Exceptions\Exceptions\Program.cs:linje 10

What it says is not that important though in this case as we're not going to
analyze the exception I had thrown there. Rather just look at the last line. It
tells us which fail and what line the exception was thrown at and that way we
can find out what went wrong in our code.

Though it's not always we want the errors to stp our program from running and
errors can happen even when they aren't suppose to, so that's why we can
wrap a try/catch around some code. In that case it will try to execute
something and if it fails it will jump to the catch block. Notice that you shouldn't
use try/catches everywhere as they will slow down your performance if used
heavily. Only use them when necessary.

So the exception I had was telling me that the input string was not in a correct
format and which is correct. I was parsing a string to an int, though the string I
was parsing was "s" which is not a propert integer.

Code:

int p = int.Parse("s");

Now what if we put a try/catch around it, will our application stop? No.
So let's try that.
Code:

try
{
int p = int.Parse("s");
}
catch
{

You can also catch the exceptions in case you still want to show the errors
thrown. You can do that by calling the exception class as a parameter for the
catch block.

Code:

try
{
int p = int.Parse("s");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

You can also throw your own exceptions or create your own exception, so let's
look at that.

To throw an exception you'll just use the throw keyword and then a new
instance of Exception.

Code:

throw new Exception("This is an exception thrown!");

What about creating custom exceptions? Basically you'd just inherit the
Exception class and the constructor for Exception takes a string as parameter
which can be used as your exception message.

Code:
public class MyException : Exception
{
public MyException()
: base("A custom exception.")
{

}
}
Now you can just throw MyException ;)

That was a bit about exceptions and error handling. There is a lot more to it
though.

Вам также может понравиться