7/23/2019 C_Sharp Tutorial Em Ingls
1/33
C-Sharp Tutorial em Ingls
Welcome to this C# tutorial. With the introduction of the .NETframework !icrosoft included a new language called C#"pronounced C Sharp. C# is designed to $e a simple modern
general-purpose o$%ect-oriented programming language$orrowing ke& concepts from se'eral other languages mostnota$l& (a'a.
C# could theoreticall& $e compiled to machine code $ut inreal life it)s alwa&s used in com$ination with the .NETframework. Therefore applications written in C# re*uiresthe .NET framework to $e installed on the computer runningthe application. While the .NET framework makes it possi$leto use a wide range of languages C# is sometimes referred toas T+E .NET language perhaps $ecause it was designedtogether with the framework.
C# is an ,$%ect ,riented language and does not oer glo$al'aria$les or functions. E'er&thing is wrapped in classes e'ensimple t&pes like int and string which inherits from theS&stem.,$%ect class.
In the following chapters &ou will $e guided through the mostimportant topics a$out C#.
Hello, world!
If you have ever learned a programming language, you know that they all startwith the "Hello, world!" example, and who are we to break such a fine
tradition? Start isual #xpress $introduced in the last chapter%, and select
&ile '( )ew pro*ect+ &rom the pro*ect dialog, select the onsole application-his is the most basic application type on a .indows system, but don/t worry,we won/t stay here for long 0nce you click 0k, isual #xpress creates a
new pro*ect for you, including a file called 1rogramcs -his is where all thefun is, and it should look something like this2
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
7/23/2019 C_Sharp Tutorial Em Ingls
2/33
static void Main(string! args"
{
#
#
#
3ctually, all these lines doesn/t really accomplish anything, or at least it may
seem so -ry running the application by pushing &4 on your keyboard -hiswill make isual #xpress compile and execute your code, but as you will
see, it doesn/t do much 5ou will likely *ust see a black window launch andclose again -hat is because our application doesn/t do anything yet In the
next chapter we will go through these lines to see what they are all about, butfor now, we really would like to see some results, so let/s pretend that we
know all about and add a couple of lines to get some output .ithin thelast set of 6 7, add these lines2
Console.$rite%ine(&'ello )orld*&";
Console.+ead%ine(";
-he code of your first application should now look like this2using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string! args"
{
Console.$rite%ine(&'ello )orld*&";
Console.+ead%ine("; #
#
#
0nce again, hit &4 to run it, and you will see the black window actually
staying, and even displaying our greeting to the world 0kay, so we added two
lines of code, but what to they do? 0ne of the nice things about and the
)#- framework is the fact that a lot of the code makes sense even to the
untrained eye, which this example shows
The rst line uses the Console class to output a line of te/tand the second one reads a line of te/t from the console.0ead1 Wh&1 2ctuall& this is a $it of a trick since without itthe application would %ust end and close the window with theoutput $efore an&one could see it.
The 0ead3ine command tells the application to wait for inputfrom the user and as &ou will notice the console window nowallows &ou to enter te/t. 4ress Enter to close it.
Congratulations &ou ha'e %ust created &our rst C#
7/23/2019 C_Sharp Tutorial Em Ingls
3/33
application5 0ead on in the ne/t chapter for e'en moreinformation a$out what)s actuall& going on.
+ello world e/plained
In the previous chapter, we tried writing a piece of text to the console, in ourfirst application -o see some actual progress, we didn/t go into muchdetail about the lines of code we used, so this chapter is an explanation of the
Hello world example code 3s you can probably see from the code, some ofthe lines look similar, so we will bring them back in groups for an individual
explanation 8et/s start with the shortest and most common characters in ourcode2 -he 6 and 7 -hey are often referred to as curly braces, and in , they
mark the beginning and end of a logical block of code -he curly braces areused in lots of other languages, including 99, :ava, :avaScript and many
others 3s you can see in the code, they are used to wrap several lines of code
which belongs together In later examples, it will be clearer how they areused
)ow let/s start from the beginning2using System;
using System.Collections.Generic;
using System.Text;
using is a keyword, highlighted with blue by the editor -he using keyword
imports a namespace, and a namespace is a collection of classes lassesbrings us some sort of functionality, and when working with an advanced I;#
like isual #xpress, it will usually create parts of the trivial code for us Inthis case, it created a class for us, and imported the namespaces which is
re is now the main namespace for thisapplication, and new classes will be a part of it by default 0bviously, you can
change this, and create classes in another namespace In that case, you willhave to import this new namespace to use it in your application, with the using
statement, like any other namespace
)ext, we define our class Since is truly an 0b*ect 0riented language,every line of code that actually does something, is wrapped inside a class In
the case, the class is simply called 1rogram2class Program
.e can have more classes, even in the same file &or now, we only need oneclass 3 class can contain several variables, properties and methods, concepts
we will go deeper into later on &or now, all you need to know is that ourcurrent class only contains one method and nothing else It/s declared like this2
7/23/2019 C_Sharp Tutorial Em Ingls
4/33
static void Main(string! args"
-his line is probably the most complicated one in this example, so let/s split it
up a bit -he first word is static -he static keyword tells us that this method
should be accesible without instantiating the class, but more about this in our
chapter about classes
-he next keyword is void, and tells us what this method should return &or
instance, int could be an integer or a string of text, but in this case, we don/t
want our method to return anything, or void, which is the same as no type
-he next word is Main, which is simply the name of our method -his method
is the so'called entry'point of our application, that is, the first piece of code to
be executed, and in our example, the only piece to be executed
Now after the name of a method a set of arguments can $especied within a set of parentheses. In our e/ample ourmethod takes onl& one argument called args. The t&pe of theargument is a string or to $e more precise an arra& ofstrings $ut more on that later. If &ou think a$out it thismakes perfect sense since Windows applications can alwa&s$e called with an optinal set of arguments. These argumentswill $e passed as te/t strings to our main method.
2nd that)s it. 6ou should now ha'e a $asic understanding ofour rst C# application as well as the $asic principles of whatmakes a console application work.
7ata T&pes
7ata t&pes are used e'er&where in a programming languagelike C#. 8ecause it)s a strongl& t&ped language &ou arere*uired to inform the compiler a$out which data t&pes &ouwish to use e'er& time &ou declare a 'aria$le as &ou will see
in the chapter a$out 'aria$les. In this chapter we will take alook at some of the most used data t&pes and how the& work.
boolis one of the simplest data t&pes. It can contain onl& 9'alues - false or true. The $ool t&pe is important tounderstand when using logical operators like the ifstatement.
intis short for integer a data t&pe for storing num$erswithout decimals. When working with num$ers int is the most
7/23/2019 C_Sharp Tutorial Em Ingls
5/33
commonl& used data t&pe. Integers ha'e se'eral data t&peswithin C# depending on the si:e of the num$er the& aresupposed to store.
stringis used for storing te/t that is a num$er of chars. InC# strings are immuta$le which means that strings arene'er changed after the& ha'e $een created. When usingmethods which changes a string the actual string is notchanged - a new string is returned instead.
charis used for storing a single character.
foatis one of the data t&pes used to store num$ers which
ma& or ma& not contain decimals.
;aria$les
3 variable can be compared to a storage room, and is essential for the
programmer In , a variable is declared like this2
data type( name(@
3n example could look like this2
string name@
-hat/s the most basic version Asually, you wish to assign a visibility to the
variable, and perhaps assign a value to it at the same time It can be done likethis2
visibility( data type( name( B value(@
3nd with an example2
private string name , &-on /oe&;-he visibility part is explained elsewhere in this tutorial, so let/s concentrate
on the variable part .e will *ump straight to an example of actually using acouple of them2using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string! args"
{
string 0irstame , &-on&; string lastame , &/oe&;
7/23/2019 C_Sharp Tutorial Em Ingls
6/33
Console.$rite%ine(&ame2 & 3 0irstame 3 & & 3 lastame";
Console.$rite%ine(&Please enter a ne) 0irst name2&";
0irstame , Console.+ead%ine(";
Console.$rite%ine(&e) name2 & 3 0irstame 3 & & 3
lastame";
Console.+ead%ine(";
#
#
#
0kay, a lot of this has already been explained, so we will *ump directly to the
interesting part &irst of all, we declare a couple of variables of the string type
3 string simply contains text, as you can see, since we give them a value
straight away )ext, we output a line of text to the console, where we use the
two variables -he string is made up by using the 9 characters to "collect" the
different parts
)ext, we urge the user to enter a new first name, and then we use the
Cead8ine$% method to read the user input from the console and into the
first)ame variable 0nce the user presses the #nter key, the new first name is
assigned to the variable, and in the next line we output the name presentation
again, to show the change .e have *ust used our first variable and the single
most important feature of a variable2 -he ability to change its value at
runtime
3nother interesting example is doing math Here is one, based on a lot of thesame code we have *ust used2int num4er1 num4er5;
Console.$rite%ine(&Please enter a num4er2&";
num4er1 , int.Parse(Console.+ead%ine("";
Console.$rite%ine(&Tan6 you. 7ne more2&";
num4er5 , int.Parse(Console.+ead%ine("";
Console.$rite%ine(&Adding te t)o num4ers2 & 3 (num4er1 3 num4er5"";
Console.+ead%ine(";
1ut this in our Dain method, and try it out -he only new "trick" we use here,
is the int1arse$% method It simply reads a string and converts it into an
integer 3s you can see, this application makes no effort to validate the user
input, and if you enter something which is not a number, an exception will be
raised Dore about those later
-he if Statement
0ne of the single most important statements in every programming language
is the if statement Eeing able to set up conditional blocks of code is afundamental principal of writing software In , the if statement is very
7/23/2019 C_Sharp Tutorial Em Ingls
7/33
simple to use If you have already used another programming language,
chances are that you can use the if statement of straight away In any case,read on to see how it/s used -he if statement needs a boolean result, that is,
true or false In some programming languages, several datatypes can beautomatically converted into booleans, but in , you have to specifically
make the result boolean &or instance, you can/t use if$number%, but you cancompare number to something, to generate a true or false, like we do later on
In the previous chapter we looked at variables, so we will expand on one of
the examples to see how conditional logic can be usedusing System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string! args" {
int num4er;
Console.$rite%ine(&Please enter a num4er 4et)een 8 and
182&";
num4er , int.Parse(Console.+ead%ine("";
i0(num4er 9 18"
Console.$rite%ine(&'ey* Te num4er sould 4e 18 or
less*&";
else
i0(num4er : 8"
Console.$rite%ine(&'ey* Te num4er sould 4e 8 ormore*&";
else
Console.$rite%ine(&Good o4*&";
Console.+ead%ine(";
#
#
#
.e use F if statements to check if the entered number is between G and >G,
and a companion of the if statement2 -he else keyword Its meaning should be
obvious to anyone speaking #nglish ' it simply offers an alternative to the
code being executed if the condition of the if statement is not met
3s you may have noticed, we don/t use the 6 and 7 characters to define the
conditional blocks of code -he rule is that if a block only contains a singleline of code, the block characters are not re
7/23/2019 C_Sharp Tutorial Em Ingls
8/33
.e put each condition in a set of parentheses, and then we use the operator,
which simply means "or", to check if the number is either more than >G 0Cless than G 3nother operator you will be using a lot is the 3); operator,
which is written like this2 ould we have used the 3); operator instead?0f course, we simply turn it around a bit, like this2i0((num4er :, 18" == (num4er 9, 8""
Console.$rite%ine(&Good o4*&";
else
Console.$rite%ine(&'ey* Te num4er sould 4e 8 or more and 18 or
less*&";
-his introduces a couple of new operators, the "less than or eero*&";
4rea6;
case 12
Console.$rite%ine(&Te num4er is one*&";
4rea6;
#
-he identifier to check is put after the switch keyword, and then there/s the listof case statements, where we check the identifier against a given value 5ouwill notice that we have a break statement at the end of each case simply
re
7/23/2019 C_Sharp Tutorial Em Ingls
9/33
against our lowercase strings, so that there is no difference between lowercase
and uppercase letters
Still, the user might make a typo or try writing something completelydifferent, and in that case, no output will be generated by this specific switch
statement #nter the default keyword!Console.$rite%ine(&/o you enoy C? @ (yesnomay4e"&";
string input , Console.+ead%ine(";
s)itc(input.To%o)er(""
{
case &yes&2
case &may4e&2
Console.$rite%ine(&Great*&";
4rea6;
case &no&2
Console.$rite%ine(&Too 4ad*&";
4rea6;
de0ault2
Console.$rite%ine(&Bm sorry B dont understand tat*&"; 4rea6;
#
If none of the case statements has evaluated to true, then the default statement,
if any, will be executed It is optional, as we saw in the previous examples
8oops
2nother essential techni*ue when writing software is looping -the a$ilit& to repeat a $lock of code < times. In C# the& comein = dierent 'ariants and we will ha'e a look at each one ofthem.
The while loop
The while loop is pro$a$l& the most simple one so we willstart with that. The while loop simpl& e/ecutes a $lock of codeas long as the condition &ou gi'e it is true. 2 small e/ampleand then some more e/planation>
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string! args"
{
int num4er , 8;
)ile(num4er : D"
{
Console.$rite%ine(num4er";
num4er , num4er 3 1;
#
Console.+ead%ine(";
#
7/23/2019 C_Sharp Tutorial Em Ingls
10/33
#
#
Tr& running the code. 6ou will get a nice listing of num$ersfrom ? to =. The num$er is rst dened as ? and each timethe code in the loop is e/ecuted it)s incremented $& one. 8ut
wh& does it onl& get to = when the code sa&s @1 Aor thecondition to return true the num$er has to $e less than @which in this case means that the code which outputs thenum$er is not reached once the num$er is e*ual to @. This is$ecause the condition of the while loop is e'aluated $efore itenters the code $lock.
The do loop
The opposite is true for the do loop which works like the while
loop in other aspects through. The do loop e'aluates thecondition after the loop has e/ecuted which makes sure thatthe code $lock is alwa&s e/ecuted at least once.
do
{
Console.$rite%ine(num4er";
num4er , num4er 3 1;
# )ile(num4er : D";
The output is the same though - once the num$er is morethan @ the loop is e/ited.
The for loopThe for loop is a $it dierent. It)s preferred when &ou knowhow man& iterations &ou want either $ecause &ou know thee/act amount of iterations or $ecause &ou ha'e a 'aria$lecontaining the amount. +ere is an e/ample on the for loop.
using System;
namespace ConsoleApplication1
{
class Program
{ static void Main(string! args"
{
int num4er , D;
0or(int i , 8; i : num4er; i33"
Console.$rite%ine(i";
Console.+ead%ine(";
#
#
#
This produces the e/act same output $ut as &ou can see thefor loop is a $it more compact. It consists of B parts - we
7/23/2019 C_Sharp Tutorial Em Ingls
11/33
initiali:e a 'aria$le for counting set up a conditionalstatement to test it and increment the counter " meansthe same as D'aria$le 'aria$le FD.
The rst part where we dene the i 'aria$le and set it to ? isonl& e/ecuted once $efore the loop starts. The last 9 partsare e/ecuted for each iteration of the loop. Each time i iscompared to our num$er 'aria$le - if i is smaller than num$erthe loop runs one more time. 2fter that i is increased $& one.
Tr& running the program and afterwards tr& changing thenum$er 'aria$le to something $igger or smaller than @. 6ouwill see the loop respond to the change.
The foreach loopThe last loop we will look at is the foreach loop. It operates oncollections of items for instance arra&s or other $uilt-in listt&pes. In our e/ample we will use one of the simple listscalled an 2rra&3ist. It works much like an arra& $ut don)tworr& we will look into it in a later chapter.
using System;
using System.Collections;
namespace ConsoleApplication1
{ class Program
{
static void Main(string! args"
{
Array%ist list , ne) Array%ist(";
list.Add(&-on /oe&";
list.Add(&-ane /oe&";
list.Add(&Someone Else&";
0oreac(string name in list"
Console.$rite%ine(name";
Console.+ead%ine("; #
#
#
,ka& so we create an instance of an 2rra&3ist and then weadd some string items to it. We use the foreach loop to runthrough each item setting the name 'aria$le to the item weha'e reached each time. That wa& we ha'e a named 'aria$leto output. 2s &ou can see we declare the name 'aria$le to $eof the string t&pe G &ou alwa&s need to tell the foreach loop
which datat&pe &ou are e/pecting to pull out of the collection.In case &ou ha'e a list of 'arious t&pes &ou ma& use the
7/23/2019 C_Sharp Tutorial Em Ingls
12/33
o$%ect class instead of a specic class to pull out each item asan o$%ect.
When working with collections &ou are 'er& likel& to $e using
the foreach loop most of the time mainl& $ecause itHs simplerthan an& of the other loops for these kind of operations.
Aunctions
3 function allows you to encapsulate a piece of code and call it from other
parts of your code 5ou may very soon run into a situation where you need torepeat a piece of code, from multiple places, and this is where functions come
in In , they are basically declared like this2:visi4ility9 :return type9 :name9(:parameters9"
{
:0unction code9#
-o call a function, you simply write its name, an open parenthesis, then
parameters, if any, and then a closing parenthesis, like this2/oStu00(";
Here is an example of our ;oStuff$% function2pu4lic void /oStu00("
{
Console.$rite%ine(&Bm doing someting...&";
#
-he first part, public, is the visibility, and is optional If you don/t define any,
then the function will be private Dore about that later on)ext is the type to return It could be any valid type in , or as we have done
it here, void 3 void means that this function returns absolutely nothing 3lso,this function takes no parameters, as you can see from the empty set of
parentheses, so it/s actually *ust a tad bit boring 8et/s change that2pu4lic int Addum4ers(int num4er1 int num4er5"
{
int result , num4er1 3 num4er5;
return result;
#
.e/ve changed almost everything -he function now returns an integer, it
takes two parameters $both integers%, and instead of outputting something, itmakes a calculation and then returns the result -his means that we can addtwo numbers from various places in our code, simply by calling this function,
instead of having to write the calculation code each time .hile we don/t savethat much time and effort in this small example, you better believe that you
will learn to love functions, the more you use -his function is called likethis2int result , Addum4ers(18 D";
Console.$rite%ine(result";
3s mentioned, this function actually returns something, and it has to, because
we told that it/s supposed to do so .hen declaring anything else than voidas a return type, we are forcing our self to return something 5ou can try
7/23/2019 C_Sharp Tutorial Em Ingls
13/33
removing the return line from the example above, and see the compiler
complain2
'AddNumbers(int, int)': not all code paths return a value
-he compiler is reminding us that we have a function which doesn/t returnsomething, although we promised 3nd the compiler is pretty clever! Instead
of removing the line, try something like this2pu4lic int Addum4ers(int num4er1 int num4er5"
{
int result , num4er1 3 num4er5;
i0(result 9 18"
{
return result;
#
#
5ou will see the exact same error ' but why? Eecause there is no guaranteethat our if statement will evaluate to true and the return line being executed5ou can solve this by having a second, default like return statement in the end2pu4lic int Addum4ers(int num4er1 int num4er5"
{
int result , num4er1 3 num4er5;
i0(result 9 18"
{
return result;
#
return 8;
#
-his will fix the problem we created for our self, and it will also show youthat we can have more than one return statement in our function 3s soon as a
return statement is reached, the function is left and no more code in it is
executed In this case, it means that as long as the result is higher than >G, the
"return G" is never reached
&unction 1arameter
In the pre'ious chapter we had a look at functions. We $rie&discussed parameters $ut onl& $rie&. While parameters are
'er& simple and straight forward to use there are tricks whichcan make them a lot more powerful.
The rst thing that we will take a look at is the out and refmodiers. C# and other languages as well dier $etweentwo parameters> D$& 'alueD and D$& referenceD. The default inC# is D$& 'alueD which $asicall& means that when &ou passon a 'aria$le to a function call &ou are actuall& sending acop& of the o$%ect instead of a reference to it. This also
means that &ou can make changes to the parameter frominside the function without aecting the original o$%ect &ou
7/23/2019 C_Sharp Tutorial Em Ingls
14/33
passed as a parameter.
With the ref and the out ke&word we can change this$eha'ior so we pass along a reference to the o$%ect instead
of its 'alue.The ref modier
Consider the following e/ample>
static void Main(string! args"
{
int num4er , 58;
AddFive(num4er";
Console.$rite%ine(num4er";
Console.+eadey(";
#
static void AddFive(int num4er"{
num4er , num4er 3 D;
#
We create an integer assign the num$er 9? to it and then weuse the 2ddAi'e" method which should add @ to the num$er.8ut does it1 No. The 'alue we assign to num$er inside thefunction is ne'er carried out of the function $ecause we ha'epassed a cop& of the num$er 'alue instead of a reference toit. This is simpl& how C# works and in a lot of cases it)s the
preferred result. +owe'er in this case we actuall& wish tomodif& the num$er inside our function. Enter the ref ke&word>
static void Main(string! args"
{
int num4er , 58;
AddFive(re0 num4er";
Console.$rite%ine(num4er";
Console.+eadey(";
#
static void AddFive(re0 int num4er"
{ num4er , num4er 3 D;
#
2s &ou can see all we)'e done is adding the ref ke&word tothe function declaration as well as the call to the function. If&ou run the program now &ou will see that the 'alue ofnum$er has now changed once we return from the functioncall.
The out modier
The out modier works prett& much like the ref modier. The&$oth ensure that the parameter is passed $& reference
7/23/2019 C_Sharp Tutorial Em Ingls
15/33
instead of $& 'alue $ut the& do come with two importantdierences> 2 'alue passed to a ref modier has to $einitiali:ed $efore calling the method - this is not true for theout modier where &ou can use un-initiali:ed 'alues. ,n the
other hand &ou can)t lea'e a function call with an outparameter without assigning a 'alue to it. Since &ou can passin un-initiali:ed 'alues as an out parameter &ou are not a$leto actuall& use an out parameter inside a function - &ou canonl& assign a new 'alue to it.
Whether to use out or ref reall& depends on the situation as&ou will reali:e once &ou start using them. 8oth are t&picall&used to work around the issue of onl& $eing a$le to return one
'alue from a function with C#.
Jsing the out modier is %ust like using the ref modier asshown a$o'e. Simpl& change the ref ke&word to the outke&word.
The params modier
So far all of our functions ha'e accepted a /ed amount ofparameters. +owe'er in some cases &ou might need a
function which takes an ar$itrar& num$er of parameters. Thiscould of course $e done $& accepting an arra& or a list as aparameter like this>
static void GreetPersons(string! names" { #
+owe'er calling it would $e a $it clums&. In the shortest formit would look like this>
GreetPersons(ne) string! { &-on& &-ane& &Tar>an& #";
It is accepta$le $ut it can $e done e'en smarter with theparams ke&word>
static void GreetPersons(params string! names" { #
Calling it would then look like this>
GreetPersons(&-on& &-ane& &Tar>an&";
2nother ad'antage of using the params approach is that &ouare allowed to pass :ero parameters to it as well.Aunctions with params can e'en take other parameters aswell as long as the parameter with the params ke&word arethe last one. 8esides that onl& one parameter using the
params ke&word can $e used per function. +ere is a last andmore complete e/ample>
7/23/2019 C_Sharp Tutorial Em Ingls
16/33
static void Main(string! args"
{
GreetPersons(8";
GreetPersons(5D &-on& &-ane& &Tar>an&";
Console.+eadey(";
#
static void GreetPersons(int someHnusedParameter params string!
names"
{
0oreac(string name in names"
Console.$rite%ine(&'ello & 3 name";
#
2rra&s
3rrays works as collections of items, for instance strings 5ou can use them togather items in a single group, and perform various operations on them, eg
sorting Eesides that, several methods within the framework work on arrays,to make it possible to accept a range of items instead of *ust one -his factalone makes it important to know a bit about arrays
3rrays are declared much like variables, with a set of JK brackets after the
datatype, like this2string! names;
5ou need to instantiate the array to use it, which is done like this2string! names , ne) string5!;
-he number $F% is the siLe of the array, that is, the amount of items we can put
in it 1utting items into the array is pretty simple as well2names8! , &-on /oe&;
Eut why G? 3s it is with so many things in the world of programming, the
counting starts from G instead of > So the first item is indexed as G, the nextas > and so on 5ou should remember this when filling the array with items,
because overfilling it will cause an exception .hen you look at the initialiLer,setting the array to a siLe of F, it might seem natural to put item number G, >
and F into it, but this is one item too much If you do it, an exception will bethrown .e will discuss exceptions in a later chapter
#arlier, we learned about loops, and obviously these go great with arrays -hemost common way of getting data out of an array, is to loop through it and
perform some sort of operation with each value 8et/s use the array from
before, to make a real example2using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string! args"
{
string! names , ne) string5!;
7/23/2019 C_Sharp Tutorial Em Ingls
17/33
names8! , &-on /oe&;
names1! , &-ane /oe&;
0oreac(string s in names"
Console.$rite%ine(s";
Console.+ead%ine(";
#
#
#
.e use the foreach loop, because it/s the easiest, but of course we could have
used one of the other types of loop instead -he for loop is good with arrays aswell, for instance if you need to count each item, like this20or(int i , 8; i : names.%engt; i33"
Console.$rite%ine(&Btem num4er & 3 i 3 &2 & 3 namesi!";
It/s actually very simple .e use the 8ength property of the array to decide
how many times the loop should iterate, and then we use the counter $i% to
output where we are in the process, as well as get the item from the array :ust
like we used a number, a so called indexer, to put items into the array, we can
use it to get a specific item out again
I told you earlier that we could use an array to sort a range of values, and it/s
actually very easy -he 3rray class contains a bunch of smart methods forworking with arrays -his example will use numbers instead of strings, *ust to
try something else, but it could *ust as easily have been strings I wish to showyou another way of populating an array, which is much easier if you have a
small, predefined set of items that you wish to put into your array -ake alook2int! num4ers , ne) intD! { I J K 8 D #;
.ith one line, we have created an array with a siLe of 4, and filled it with 4
integers Ey filling the array like this, you get an extra advantage, since thecompiler will check and make sure that you don/t put too many items into the
array -ry adding a number more ' you will see the compiler complain aboutit
3ctually, it can be done even shorter, like this2int! num4ers , { I J K 8 D #;
-his is short, and you don/t have to specify a siLe -he first approach may beeasier to read later on though
8et/s try sorting the array ' here/s a complete example2using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string! args" {
int! num4ers , { I J K 8 D #;
7/23/2019 C_Sharp Tutorial Em Ingls
18/33
Array.Sort(num4ers";
0oreac(int i in num4ers"
Console.$rite%ine(i";
Console.+ead%ine("; #
#
#
-he only real new thing here is the 3rraySort command It can take various
parameters, for various kinds of sorting, but in this case, it simply takes our
array 3s you can see from the result, our array has been sorted -he 3rray
class has other methods as well, for instance the Ceverse$% method 5ou can
look it up in the documentation to see all the features of the 3rray class
-he arrays we have used so far have only had one dimension However, arrays can be multidimensional, sometimes referred to as arrays in arrays
Dultidimensional arrays come in two flavors with 2 Cectangular arrays and
*agged arrays -he difference is that with rectangular arrays, all the
dimensions have to be the same siLe, hence the name rectangular 3 *agged
array can have dimensions of various siLes Dultidimensional arrays are a
heavy sub*ect, and a bit out of the scope of this tutorial
lasses
Introduction to lassesIn lots of programming tutorials, information about classes will be saved formuch later However, since is all about 0b*ect 0riented programming and
thereby classes, we will make a basic introduction to the most important stuffalready now
&irst of all, a class is a group of related methods and variables 3 class
describes these things, and in most cases, you create an instance of this class,now referred to as an ob*ect 0n this ob*ect, you use the defined methods and
variables 0f course, you can create as many instances of your class as youwant to lasses, and 0b*ect 0riented programming in general, is a huge
topic .e will cover some of it in this chapter as well as in later chapters, butnot all of it
In the Hello world chapter, we saw a class used for the first time, since
everything in is built upon classes 8et/s expand our Hello world examplewith a class we built on our ownusing System;
namespace ConsoleApplication1
{ class Program
7/23/2019 C_Sharp Tutorial Em Ingls
19/33
{
static void Main(string! args"
{
Car car;
car , ne) Car(&+ed&";
Console.$rite%ine(car./escri4e("";
car , ne) Car(&Green&";
Console.$rite%ine(car./escri4e("";
Console.+ead%ine(";
#
#
class Car
{
private string color;
pu4lic Car(string color"
{
tis.color , color;
#
pu4lic string /escri4e("
{
return &Tis car is & 3 Color;
#
pu4lic string Color
{
get { return color; #
set { color , value; #
#
#
#
0kay, lots of new stuff here, but almost all of it is based on stuff we/ve already
used earlier in this tutorial 3s you can see, we have defined a new class,
called ar It/s declared in the same file as our main application, for an easier
overview, however, usually new classes are defined in their own files It
defines a single variable, called color, which of course is used to tell the color
of our car .e declared it as private, which is good practice ' accessing
variables from the outside should be done using a property -he olor
property is defined in the end of the class, giving access to the color variable
8esides that our Car class denes a constructor. It takes aparameter which allows us to initiali:e Car o$%ects with acolor. Since there is onl& one constructor Car o$%ects can onl&$e instantiated with a color. The 7escri$e" method allows usto get a nice message with the single piece of informationthat we record a$out our. It simpl& returns a string with the
information we pro'ide.
7/23/2019 C_Sharp Tutorial Em Ingls
20/33
Now in our main application we declare a 'aria$le of thet&pe Car. 2fter that we create a new instance of it with D0edDas parameter. 2ccording to the code of our class this meansthat the color red will $e assigned as the color of the car. To
'erif& this we call the 7escri$e" method and to show howeas& we can create se'eral instances of the same class we doit again $ut with another color. We ha'e %ust created our rstfunctional class and used it.
In the following chapters concepts like propertiesconstructors and 'isi$ilit& will $e e/plained in more depth.
4roperties
1roperties allow you to control the accessibility of a classes variables, and isthe recommended way to access variables from the outside in an ob*ectoriented programming language like In our chapter on classes, we saw the
use of a property for the first time, and the concept is actually
7/23/2019 C_Sharp Tutorial Em Ingls
21/33
0kay, we have *ust made our property a bit more advanced -he color variable
will now be returned in uppercase characters, since we apply the -oApper$%
method to it before returning it, and when we try to set the color, only the
value "Ced" will be accepted Sure, this example is not terrible useful, but it
shows the potential of propertiesConstructors and destructors
onstructors are special methods, used when instantiating a class 3
constructor can never return anything, which is why you don/t have to define areturn type for it 3 normal method is defined like this2pu4lic string /escri4e("
3 constructor can be defined like this2pu4lic Car("
In our example for this chapter, we have a ar class, with a constructor which
takes a string as argument 0f course, a constructor can be overloaded as well,meaning we can have several constructors, with the same name, but different
parameters Here is an example2pu4lic Car("
{
#
pu4lic Car(string color"
{
tis.color , color;
#
3 constructor can call another constructor, which can come in handy inseveral situations Here is an example2pu4lic Car("
{
Console.$rite%ine(&Constructor )it no parameters called*&";
#
pu4lic Car(string color" 2 tis("
{
tis.color , color;
Console.$rite%ine(&Constructor )it color parameter called*&";
#
If you run this code, you will see that the constructor with no parameters is
called first -his can be used for instantiating various ob*ects for the class inthe default constructor, which can be called from other constructors from the
class If the constructor you wish to call takes parameters, you can do that aswell Here is a simple example2pu4lic Car(string color" 2 tis("
{
tis.color , color;
Console.$rite%ine(&Constructor )it color parameter called*&";
#
pu4lic Car(string param1 string param5" 2 tis(param1"
{
#
7/23/2019 C_Sharp Tutorial Em Ingls
22/33
If you call the constructor which takes F parameters, the first parameter will
be used to invoke the constructor that takes > parameter
7estructors
Since C# is gar$age collected meaing that the framework will
free the o$%ects that &ou no longer use there ma& $e timeswhere &ou need to do some manual cleanup. 2 destructor amethod called once an o$%ect is disposed can $e used tocleanup resources used $& the o$%ect. 7estructors doesn)tlook 'er& much like other methods in C#. +ere is an e/ampleof a destructor for our Car class>
LCar("
{
Console.$rite%ine(&7ut..&";
#,nce the o$%ect is collected $& the gar$age collector thismethod is called.
!ethod ,'erloading
3 lot of programming languages supports a techni
7/23/2019 C_Sharp Tutorial Em Ingls
23/33
So, by defining several versions of the same function, how do we avoid
having the same code several places? It/s actually
7/23/2019 C_Sharp Tutorial Em Ingls
24/33
se'eral other t&pes of 'isi$ilit& within C#. +ere is a completelist and although some of them might not feel that rele'ant to&ou right now &ou can alwa&s come $ack to this page andread up on them>
public- the mem$er can $e reached from an&where. This isthe least restricti'e 'isi$ilit&. Enums and interfaces are $&default pu$licl& 'isi$le.
protected- mem$ers can onl& $e reached from within thesame class or from a class which inherits from this class.
internal- mem$ers can $e reached from within the same
pro%ect onl&.
protected internal- the same as internal e/cept that alsoclasses which inherits from this class can reach it mem$erse'en from another pro%ect.
private- can onl& $e reached $& mem$ers from the sameclass. This is the most restricti'e 'isi$ilit&. Classes and structsare $& default set to pri'ate 'isi$ilit&.
So for instance if &ou ha'e two classes ClassF and Class9pri'ate mem$ers from ClassF can onl& $e used within ClassF.
6ou can)t create a new instance of ClassF inside of Class9 andthen e/pect to $e a$le to use its pri'ate mem$ers.
If Class9 inherits from ClassF then onl& non-pri'ate mem$erscan $e reached from inside of Class9.
Static mem$ers
3s we saw in a previous chapter, the usual way to communicate with a class,
is to create a new instance of the class, and then work on the resulting ob*ectIn most cases, this is what classes are all about ' the ability to instantiate
multiple copies of the same class and then use them differently in some wayHowever, in some cases, you might like to have a class which you may use
without instantiating it, or at least a class where you can use members of itwithout creating an ob*ect for it &or instance, you may have a class with a
variable that always remains the same, no matter where and how it/s used
-his is called a static member, static because it remains the same
7/23/2019 C_Sharp Tutorial Em Ingls
25/33
3 class can be static, and it can have static members, both functions and
fields 3 static class can/t be instantiated, so in other words, it will work moreas a grouping of related members than an actual class 5ou may choose to
create a non'static class instead, but let it have certain static members 3 non'static class can still be instantiated and used like a regular class, but you can/t
use a static member on an ob*ect of the class 3 static class may only containstatic members
&irst, here is an example of a static class2pu4lic static class +ectangle
{
pu4lic static int CalculateArea(int )idt int eigt"
{
return )idt eigt;
#
#
3s you can see, we use the static keyword to mark the class as static, and thenwe use it again to mark the method, alculate3rea, as static as well If we
didn/t do that, the compiler would complain, since we can/t have a non'staticmember of a static class
-o use this method, we call it directly on the class, like this2Console.$rite%ine(&Te area is2 & 3 +ectangle.CalculateArea(D I"";
.e could add other helpful methods to the Cectangle class, but perhaps youare wondering why we are passing on width and height to the actual method,
instead of storing it inside the class and then pulling them from there when
needed? Eecause it/s static! .e could store them, but only one set ofdimensions, because there is only one version of a static class -his is veryimportant to understand
Instead, we can make the class non'static, and then have the alculate3rea as
a utility function on this class2pu4lic class +ectangle
{
private int )idt eigt;
pu4lic +ectangle(int )idt int eigt"
{ tis.)idt , )idt;
tis.eigt , eigt;
#
pu4lic void 7utputArea("
{
Console.$rite%ine(&Area output2 & 3
+ectangle.CalculateArea(tis.)idt tis.eigt"";
#
pu4lic static int CalculateArea(int )idt int eigt"
{
return )idt eigt; #
7/23/2019 C_Sharp Tutorial Em Ingls
26/33
#
3s you can see, we have made the class non'static .e have also added a
constructor, which takes a width and a height and assigns it to the instance
-hen we have added an 0utput3rea method, which uses the static method to
calculate the area -his is a fine example of mixing static members with non'
static members, in a non'static class
3 common usage of static classes, although frowned upon by some people, are
utilityMhelper classes, where you collect a bunch of useful methods, which
might not belong together, but doesn/t really seem to fit elsewhere either
Inheritance
0ne of the absolute key aspects of 0b*ect 0riented 1rogramming $001%,which is the concept that is built upon, is inheritance, the ability to create
classes which inherits certain aspects from parent classes -he entire )#-framework is built on this concept, with the "everything is an ob*ect" as a
result of it #ven a simple number is an instance of a class, which inheritsfrom the System0b*ect class, although )#- helps you out a bit, so you can
assign a number directly, instead of having to create a new instance of eg theinteger class
-his sub*ect can be a bit difficult to comprehend, but sometimes it help with
some examples, so let/s start with a simple one of those2pu4lic class Animal
{ pu4lic void Greet("
{
Console.$rite%ine(&'ello Bm some sort o0 animal*&";
#
#
pu4lic class /og 2 Animal
{
#
&irst, we define an 3nimal class, with a simple method to output a greeting
-hen we define a ;og class, and with a colon, we tell that the ;og classshould inherit from the 3nimal class -he beautiful thing about this is that it
makes sense in the real world as well ' a ;og is, obviously, an 3nimal 8et/stry using the classes2Animal animal , ne) Animal(";
animal.Greet(";
/og dog , ne) /og(";
dog.Greet(";
If you run this example, you will notice that even though we have not defined
a Oreet$% method for the ;og class, it still knows how to greet us, because itinherits this method from the 3nimal class However, this greeting is a bit
anonymous, so let/s customiLe it when we know which animal it is2pu4lic class Animal
7/23/2019 C_Sharp Tutorial Em Ingls
27/33
{
pu4lic virtual void Greet("
{
Console.$rite%ine(&'ello Bm some sort o0 animal*&";
#
#
pu4lic class /og 2 Animal
{
pu4lic override void Greet("
{
Console.$rite%ine(&'ello Bm a dog*&";
#
#
Eesides the added method on the ;og class, you should notice two things2 I
have added the virtual keyword to the method on the 3nimal class, and on the
;og class, I use the override keyword
In , you are not allowed to override a member of a class unless it/s markedas virtual If you want to, you can still access the inherited method, even whenyou override it, using the base keywordpu4lic override void Greet("
{
4ase.Greet(";
Console.$rite%ine(&Nes B am O a dog*&";
#
Dethods is not the only thing to get inherited, though In fact, pretty much all
class members will be inherited, including fields and properties :ust
remember the rules of visibilty, as discussed in a previous chapter
Inheritance is not only from one class to another ' you can have a whole
hierarchy of classes, which inherits from eachother &or instance, we could
create a 1uppy class, which inherits from our ;og class, which in turn inherits
from the 3nimal class .hat you can/t do in , is to let one class inherit from
several other classes at the same time Dultiple inheritance, as it/s called, is
not supported by
3bstract lasses
3bstract classes, marked by the keyword abstract in the class definition, aretypically used to define a base class in the hierarchy .hat/s special aboutthem, is that you can/t create an instance of them ' if you try, you will get a
compile error Instead, you have to subclass them, as taught in the chapter oninheritance, and create an instance of your subclass So when do you need an
abstract class? It really depends on what you do
-o be honest, you can go a long way without needing an abstract class, butthey are great for specific things, like frameworks, which is why you will find
7/23/2019 C_Sharp Tutorial Em Ingls
28/33
are very often, if not always, used to describe something abstract, something
that is more of a concept than a real thing
In this example, we will create a base class for four legged animals and thencreate a ;og class, which inherits from it, like this2namespace A4stractClasses
{
class Program
{
static void Main(string! args"
{
/og dog , ne) /og(";
Console.$rite%ine(dog./escri4e("";
Console.+eadey(";
#
#
a4stract class Four%eggedAnimal
{
pu4lic virtual string /escri4e("
{
return &ot muc is 6no)n a4out tis 0our legged animal*&;
#
#
class /og 2 Four%eggedAnimal
{
#
#
If you compare it with the examples in the chapter about inheritance, youwon/t see a big difference In fact, the abstract keyword in front of the&our8egged3nimal definition is the biggest difference 3s you can see, we
create a new instance of the ;og class and then call the inherited ;escribe$%method from the &our8egged3nimal class )ow try creating an instance of
the &our8egged3nimal class instead2Four%eggedAnimal someAnimal , ne) Four%eggedAnimal(";
5ou will get this fine compiler error2
Cannot create an instance of the abstract class or interface
'AbstractClasses.FourLeggedAnimal'
)ow, as you can see, we *ust inherited the ;escribe$% method, but it isn/t veryuseful in it/s current form, for our ;og class 8et/s override it2class /og 2 Four%eggedAnimal
{
pu4lic override string /escri4e("
{
return &Tis 0our legged animal is a /og*&;
#
#
In this case, we do a complete override, but in some cases, you might want touse the behavior from the base class in addition to new functionality -his can
be done by using the base keyword, which refers to the class we inherit from2
7/23/2019 C_Sharp Tutorial Em Ingls
29/33
a4stract class Four%eggedAnimal
{
pu4lic virtual string /escri4e("
{
return &Tis animal as 0our legs.&;
#
#
class /og 2 Four%eggedAnimal
{
pu4lic override string /escri4e("
{
string result , 4ase./escri4e(";
result 3, & Bn 0act its a dog*&;
return result;
#
#
)ow obviously, you can create other subclasses of the &our8egged3nimalclass ' perhaps a cat or a lion? In the next chapter, we will do a more advanced
example and introduce abstract methods as well Cead on
Dore 3bstract lasses
In the previous chapter, we had a look at abstract classes In this chapter, wewill expand the examples a bit, and throw in some abstract methods as well
3bstract methods are only allowed within abstract classes -heir definitionwill look like a regular method, but they have no code inside them2
a4stract class Four%eggedAnimal
{
pu4lic a4stract string /escri4e(";
#
So, why would you want to define an empty method that does nothing?
Eecause an abstract method is an obligation to implent that very method in allsubclasses In fact, it/s checked at compile time, to ensure that your subclasses
has this method defined 0nce again, this is a great way to create a base class
for something, while still maintaining a certain amount of control of what thesubclasses should be able to do .ith this in mind, you can always treat asubclass as its baseclass, whenever you need to use methods defined asabstract methods on the baseclass &or instance, consider the following
example2
namespace A4stractClasses
{
class Program
{
static void Main(string! args" {
7/23/2019 C_Sharp Tutorial Em Ingls
30/33
System.Collections.Array%ist animal%ist , ne)
System.Collections.Array%ist(";
animal%ist.Add(ne) /og("";
animal%ist.Add(ne) Cat("";
0oreac(Four%eggedAnimal animal in animal%ist"
Console.$rite%ine(animal./escri4e("";
Console.+eadey("; #
#
a4stract class Four%eggedAnimal
{
pu4lic a4stract string /escri4e(";
#
class /og 2 Four%eggedAnimal
{
pu4lic override string /escri4e("
{
return &Bm a dog*&;
#
#
class Cat 2 Four%eggedAnimal
{
pu4lic override string /escri4e("
{
return &Bm a cat*&;
#
#
#
3s you can see, we create an 3rray8ist to contain our animals .e then
instantiate a new dog and a new cat and add them to the list -hey are
instantiated as a ;og and a at respectively, but they are also of the type
&our8egged3nimal, and since the compiler knows that subclasses of that class
contains the ;escribe$% method, you are actually allowed to call that method,
without knowing the exact type of animal So by typecasting to the
&our8egged3nimal, which is what we do in the foreach loop, we get access to
members of the subclasses -his can be very useful in lots of scenarios
Interfaces
In previous chapters, we had a look at abstract classes Interfaces are muchlike abstract classes and they share the fact that no instances of them can be
created However, interfaces are even more conceptual than abstract classes,since no method bodies are allowed at all So an interface is kind of like an
abstract class with nothing but abstract methods, and since there are nomethods with actual code, there is no need for any fields 1roperties are
allowed though, as well as indexers and events 5ou can consider an interface
as a contract ' a class that implements it is re
7/23/2019 C_Sharp Tutorial Em Ingls
31/33
doesn/t allow multiple inheritance, where classes inherit more than a single
base class, it does in fact allow for implementation of multiple interfaces!
So, how does all of this look in code? Here/s a pretty complete example Havea look, perhaps try it out on your own, and then read on for the full
explanation2
using System;
using System.Collections.Generic;
namespace Bnter0aces
{
class Program
{
static void Main(string! args"
{
%ist:/og9 dogs , ne) %ist:/og9("; dogs.Add(ne) /og(&Fido&"";
dogs.Add(ne) /og(&o4&"";
dogs.Add(ne) /og(&Adam&"";
dogs.Sort(";
0oreac(/og dog in dogs"
Console.$rite%ine(dog./escri4e("";
Console.+eadey(";
#
#
inter0ace BAnimal
{
string /escri4e(";
string ame
{
get;
set;
#
#
class /og 2 BAnimal BCompara4le
{
private string name;
pu4lic /og(string name" {
tis.ame , name;
#
pu4lic string /escri4e("
{
return &'ello Bm a dog and my name is & 3 tis.ame;
#
pu4lic int CompareTo(o4ect o4"
{
i0(o4 is BAnimal"
return tis.ame.CompareTo((o4 as BAnimal".ame"; return 8;
#
7/23/2019 C_Sharp Tutorial Em Ingls
32/33
pu4lic string ame
{
get { return name; #
set { name , value; #
#
##
8et/s start in the middle, where we declare the interface 3s you can see, the
only difference from a class declaration, is the keyword used ' interface
instead of class 3lso, the name of the interface is prefixed with an I for
Interface ' this is simply a coding standard, and not a re
7/23/2019 C_Sharp Tutorial Em Ingls
33/33
dogs. 2nd how does the list know that our 7og o$%ect can do%ust that and which method to call to get the dogs compared18ecause we told it so $& implementing an interface thatpromises a CompareTo method5 This is the real $eaut& of
interfaces.
ContinuaLMo do tutorial est neste link> http>KKcsharp.net-
tutorials.comKclassesKinterfacesK
http://csharp.net-tutorials.com/classes/interfaces/http://csharp.net-tutorials.com/classes/interfaces/http://csharp.net-tutorials.com/classes/interfaces/http://csharp.net-tutorials.com/classes/interfaces/Top Related