Csharp Tutorial
Csharp Tutorial
Regards,
BaussHacker.
Page 4. C# Introduction
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.
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.
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".
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:
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.
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.
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()
{
}
}
Code:
MyMethod();
Code:
Myclass.MyMethod();
Code:
Mynamespace.Myclass.MyMethod();
Code:
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.
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:
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)
{
}
Code:
MyMethod("parameter1", "parameter2");
Code:
Now I don't really explain where to put this now and it may confuse you, but
remember what I explained about scopes?
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.
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();
}
}
}
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:
Code:
string
Then we have:
Code:
myString
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:
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:
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;
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.
.
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.
An example:
Code:
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:
The code above will remove Hello and the first space from myString, which will
leave us with Hack Forums!
Example #2:
Code:
An example:
Code:
Code:
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:
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.
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.
Code:
Code:
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:
Code:
If there is enough money it should remove the money and then give the beers.
Code:
Code:
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!!
Code:
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.
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:
Switch:
Code:
case false:
{
Console.WriteLine("Not Enough.");
break;
}
}
You want to use switch in the following code, however the result is the same.
Code:
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:
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.
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.
Code:
Code:
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:
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:
Code:
Code:
Code:
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.
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.
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.
Code:
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 ;).
Code:
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:
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.
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.
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;
Example:
Code:
Example:
Code:
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:
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:
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:
Code:
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.
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:
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:
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.
Code:
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:
myDictionary.Add("Hello", 41521);
myDictionary.Add("Hack Forums", 5121251);
Key example:
Code:
Value example:
Code:
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.
Code:
class Person
{
}
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.)
The name should of course be a string, because it's a "word" and consists of
alphabetic characters.
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.
Code:
Example:
Code:
myPerson.Age = 10;
myPerson.Name = "Bob";
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:
Code:
Now let's try make two new instances of these two persons.
Code:
Now what we can do is write to the console if a person has boobs or not.
Code:
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.
Code:
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.
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.
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.
Code:
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.
Code:
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:
Code:
Code:
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:
Now let's look at parameters and the ref and out keyword used with
parameters.
What I will do is pass a string and print to the console what was passed.
Code:
You should know by now how to pass a parameter to a method, but if you're in
doubt:
Code:
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:
Now if we make the parameter a ref parameter then it will actually change
value.
Code:
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:
public static void MyMethod(out string myParam) // tells it that it's an out
parameter
{
Console.Write("Write something: ");
myParam = Console.ReadLine();
}
Code:
Code:
Code:
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.)
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!
Code:
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:
Code:
public T GenericValue;
Now try to create a new instance of the class and give it a type.
Code:
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;
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:
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:
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.