string - s3.amazonaws.com

advertisement
C# 101, Lesson 2
Lesson 2: Basic Types and .NET Framework
Copyright © Vojtech
Zicha
C# 101
1
Object: Conversions, Comparisons
String: Usage, Common Methods, Characters, Comparison
Numbers: Different Types and Casting, Financial Values
Boolean: Conditions, Bitwise Flag Enumeration
Regular Expressions
I/O Manipulation
Networking API
C# 101, Lesson 2
•
•
•
•
•
•
•
Copyright © Vojtech Zicha
Agenda
2
• DONE, that is all.
• So get ready, we start!
C# 101, Lesson 2
• HEY! Go through the lesson 1!
Copyright © Vojtech Zicha
Prerequirements
3
•
•
•
•
System.Object (object)
System.String (string)
System.Int32 (int)
System.Decimal (decimal)
• The first name is the name of struct representing them. Don’t care about it
now. We use the C# keywords for them – you have them in parenthesis.
• In .NET there are many languages: PHP, Visual Basic, Python, JavaScript, Ruby,
F# and so on. In all of these languages the struct name is same, but keyword
name may differ.
• We’ll also cover converting types, do you remember what we said about
object? I promised you this topic and I haven’t forgotten yet.
C# 101, Lesson 2
• Now, we will go through all basic types we know. It is a lot of work, so we
should better start.
• This is their list. In this order we’ll visit them:
Copyright © Vojtech Zicha
Basic Types
4
• It has several methods (therefore any objects has these
methods) and 3 of them are fairly useful.
C# 101, Lesson 2
• System.Object is mother (or father, who knows?) of all
objects. Everything said about object is valid for any
other type.
Copyright © Vojtech Zicha
object
5
C# 101, Lesson 2
• Method ToString is a way how to convert any object to string.
Remember how you converted strings to integers? Very special
method and the risk of errors. Well, you can convert any object to
string using .ToString() and it shouldn’t throw any exception, sorry
raise any error.
int age = 18;
string str = age.ToString();
• You can call it even on constant, it looks weird but it is possible.
These three lines are identical (I know, the last one is just plain
stupid):
string str1 = 18.ToString();
string str2 = "18";
string str3 = "18".ToString();
Copyright © Vojtech Zicha
age.ToString()
6
C# 101, Lesson 2
• Can you guess what the following code does?
if (ageJ == ageN)
• Two == returns true, if the value of these objects is the
same. We don’t care if they are at the same memory, same
variable, we care if they are the same.
• But how can C# know if the value is the same? It uses
method Equals. Each object has its own code in this method
and therefore we can use == exactly how we want it. The
following code is the same as the code above:
if (ageJ.Equals(ageN))
Copyright © Vojtech Zicha
age.Equals()
7
• NOTE: In C/C++ you always care about memory. You have to.
But in C# you don’t have to (most times you even can’t). So
memory is not something you’d have to deal with every time.
• If you want to ask if two values are in the same memory?
• THIS CODE DOES IT! (Sorry, this code does it. I’m just
excited).
if (object.ReferenceEquals(ageJ, ageN))
• NOTE the difference between calling Equals and
ReferenceEquals methods. Remember it.
C# 101, Lesson 2
• But what if you care about memory.
Copyright © Vojtech Zicha
object.ReferenceEquals()
8
•
•
•
•
•
•
CompareTo()
Equals()
GetHashCode()
GetType()
GetTypeCode()
ToString()
• Also don’t forget ReferenceEquals() - it is kind of special
C# 101, Lesson 2
• There are also other (called instance) methods in object
class. Some of them we will use later (mainly CompareTo
and GetHashCode methods). This is their list.
Copyright © Vojtech Zicha
object: Review
9
• Remember one thing. They’re reference types (important later)
and immutable ones (important later).
• Immutable means they cannot be change. Every time you think
you’re changing string, you always create a new one.
• NOTE: If you know C/C++, you can imagine reference type as a
pointer. The string is kind of created on the heap and you have a
pointer on it. So the string is not copied, just a “pointer”. But C#
does not use pointers. It is just an analogy.
C# 101, Lesson 2
• Do you remember strings? They look easy, don’t they. Well they
are not.
Copyright © Vojtech Zicha
string
10
• NOTE: In C/C++ they wouldn’t be, so this code can seem wasteful
for you. This is C#: once you don’t need any memory, it is
automatically deleted. Even no keyword delete is in C#.
Cool, isn’t it?
C# 101, Lesson 2
• You can concatenate strings using +.
string str = "Ah" + "oj";
• This codes creates string “Ah”, string “oj” and then new string
“Ahoj”. Now add this:
str = str + "!";
• Do you think string “Ahoj” is changed? Now, it stays the same. But
new string “Ahoj!” is created and stored in str variabe. String “Ah”,
“oj” and “Ahoj” are automatically destroyed.
Copyright © Vojtech Zicha
string
11
• DO IT.
C# 101, Lesson 2
• Write a string containing from “Yo: “ and after that 200 of
“yo”. Use the for cycle.
Copyright © Vojtech Zicha
Ex. 1: Long Strings
12
C# 101, Lesson 2
• This is my solution.
string res = "Yo: ";
for (int i = 0; i < 100; i++)
{
res += "yo";
}
Console.WriteLine(res);
• (if you have used StringBuilder, you have much better
solution than me. KUDOs for you!)
Copyright © Vojtech Zicha
Ex. 1: Long Strings
13
• Let’s see it. These are the string that have to be created in our memory:
•
•
•
•
•
•
•
•
Yo:
yo
Yo: yo
yo
Yo: yoyo
yo
Yo: yoyoyo
etc.
• Do you understand? You are wasting your memory the big way. Why to create so many
strings? Because they are immutable. Remember, every time you change it, it is always
new string created. New memory taken. And so on.
C# 101, Lesson 2
• NOTE: These two line are equivalent:
res += "yo";
res = res + "yo";
• NOTE: Our solution is BAD. Very bad. Can you guess why?
Copyright © Vojtech Zicha
Ex. 1: Long Strings
14
C# 101, Lesson 2
• The class StringBuilder is a way how to compose string in
memory. So just one memory is taken, it expands.
• It has several methods, let’s see the easiest use of it and rewrite
our example to be memory efficient.
string yo = "yo";
var sb = new StringBuilder("Yo: ");
for (int i = 0; i < 100; i++)
{
sb.Append(yo);
}
string res = sb.ToString();
Console.WriteLine(res);
Copyright © Vojtech Zicha
StringBuilder
15
C# 101, Lesson 2
var sb = new StringBuilder("Yo: ");
• This is how you create a StringBuilder. It’s a very new way for you so
take a look. The argument of StringBuilder is what you start with. If you
don’t want you don’t have to provide any.
sb.Append(yo);
• Method Append adds new string to StringBuilder. It’s the most used one
– probably that’s why you use StringBuilder.
• Take a look also on AppendLine() and AppendFormat() methods.
string res = sb.ToString();
• And once our string is completed, we can fetch it from StringBuilder
using the ubiquitous method ToString().
• Now look once again on the previous example. It’s the first time you use
such a syntax, but trust me definitely not the last one. So, get familiar
with it!
Copyright © Vojtech Zicha
StringBuilder
16
string boy = "Joseph";
string girl = "Jenny";
string input = "
k and g
";
C# 101, Lesson 2
• Now, back to string.
• Have you ever seen a boring set of slides? (Don’t answer.) So now,
you will.
• We’ll go through all important methods of manipulation with strings.
• You might think: “Why?” But these are methods you use nearly all the
time and looking them up at MSDN or Object Explorer would cost
you much time.
• So, learn each method and try to use it. Be creative and get used to
them!
• All examples will use these three variables:
Copyright © Vojtech Zicha
string
17
• Method ToUpper() changes string to UPPER CASE with
respect to national language of system. If you really know
you have English, you can choose (NOT RECOMMENDED)
ToUpperInvariant().
• The same goes with ToLower().
• NOTE: Remember, that string are immutable so you cannot
changed. All these methods return the string, not change
the original one.
C# 101, Lesson 2
string boyUp = boy.ToUpper();
Console.Write(girl.ToLower());
Copyright © Vojtech Zicha
string – ToUpper() and ToLower()
18
C# 101, Lesson 2
Console.Write(input.Trim());
Console.Write(boy.Trim('J', 'h'));
• Trim() method removes (returns new string without)
whitespace from the beginning and the end. Useful when
you deal with input from the user or file.
• There are also methods TrimStart() (removes only from
beginning) and TrimEnd() (removes only from end)
• You can provide as many char arguments as you want –
then methods strip these letters from the beginning / end
of string respectively.
Copyright © Vojtech Zicha
string – Trim()
19
• String uses double quotes “”, contains many letters
• Char uses single quotes ‘’, contains one letter
• Always look whether you should provide char or string.
• To convert char to string? Use ToString() method (as
always).
• To convert string to char? Wait some slides.
• Now back to strings!
C# 101, Lesson 2
• Wait, char arguments?
• Char is a type containing just one letter. To distinguish
between char and string:
Copyright © Vojtech Zicha
char
20
• Contains() searches through the whole string and returns true if
it finds a char same as argument / substring same as argument,
otherwise it returns false.
• Useful for chechinkg – does it contain that or that? Where it is –
that’s a job for a method on next slide.
• Remember, char (single quotes) can contain just one letter. But
Contains() works faster with chars, so the code below is not the
most efficient you can get:
boy.Contains("e"); // true, not efficient
C# 101, Lesson 2
boy.Contains('e'); // true
girl.Contains("nnn"); // false
Copyright © Vojtech Zicha
string – Contains()
21
• IndexOf() searches for the first occurrence of the provided
argument in string and returns it position starting from zero. If
you provide string as argument, it returns position of the first
letter of that string.
• If the method can’t find it, it returns -1.
• The second argument specifies where to start with the lookup.
Once again, it starts counting from zero.
• The LastIndexOf() method works the same as IndexOf(), but it
searches for the last occurrence of the provided argument.
C# 101, Lesson 2
boy.IndexOf(‘e'); // 3
girl.IndexOf("nn"); // 2
girl.IndexOf('e', 3); // -1
Copyright © Vojtech Zicha
string – IndexOf(), LastIndexOf()
22
• Substring() returns part of the original string.
• First argument represents where should the part start.
Remember, it is zero based. (The index 2 represents 3rd character.)
• Second argument represents how many letters should be
returned. If you omit this one, Substring() will return everything
to the end.
• Try using these methods now, they’re fun! Don’t forget that
positions are zero-based – they start from 0, not 1.
• And get used to zero-based things. EVERYTHING in C# is zerobased.
C# 101, Lesson 2
boy.Substring(2); // seph
girl.Substring(1, 3); // enn
Copyright © Vojtech Zicha
string – Substring()
23
• StartsWith() looks at the start of the string and returns
true, if it is the same as provided argument.
• EndsWith() looks at the end of the string and returns true,
if it is the same as provided argument.
• Both function are case-sensitive, they care about lower and
upper letters.
• If you don’t want so, try to look for correct code on MSDN.
There’s a way.
C# 101, Lesson 2
boy.StartsWith("Jo"); // true
girl.EndsWith("ph"); // false
Copyright © Vojtech Zicha
string – StartsWith(), EndsWith()
24
• Length returns the number of characters in the string as a
number.
• Notice that it’s not a function – there are no parenthesis
afterwards. It’s so called property of a string – some
attribute / feature of the string.
• Didn’t understand that? Don’t worry we’ll cover that in the
very next lesson. For now remember, that the length of the
string is without parenthesis.
C# 101, Lesson 2
Console.WriteLine(boy.Length); // outputs 6
Copyright © Vojtech Zicha
string - Length
25
• Special syntax how to get one character of the string. You
use these [ ] and put a integer between them representing
the zero-based (I said everything starts from zero) index of
the character you want to get.
• NOTE for C/C++ coders: the string is not an array of chars.
I know, that this looks like it, but it is just a special syntax.
You cannot treat string as an array, but you can use this
syntax. PHP coders: you know ArrayAccess interface, right?
This is it, in C# it’s just called indexers. It works the same.
C# 101, Lesson 2
char e = boy[3]; // stores e
Copyright © Vojtech Zicha
string - Indexer
26
var arr = boy.ToCharArray();
• Remember, that there is no built-in method to convert it back to
string, here is one possible not optimized implementation using
LINQ (it runs really fast, but wastes memory):
arr.Aggregate("", (val, curr) => val + curr);
C# 101, Lesson 2
• This is just for those, who know C/C++!
The others don’t have to know about it.
• I was repeating many times, the string is not an array of chars.
But if you really want to, you can perform easy conversion using
ToCharArray() method.
Copyright © Vojtech Zicha
C/C++ NOTE: string – ToCharArray()
27
• Replace searches through the string, looks for the first
argument and replaces it with the second argument.
• You can use either two chars or two strings – but you can’t
mix it (one string and one char is prohibited).
• The methods return new string, if you use it multiple times
it can waste memory.
• Fortunately enough, StringBuilder has also method Replace
working the very same way, so you can be memory efficient.
C# 101, Lesson 2
var dboy = boy.Replace('s', 'z');
var dgirl = girl.Replace("nn", "n");
Copyright © Vojtech Zicha
string – Replace()
28
•
•
•
•
Insert()
Remove()
PadLeft()
PadRight()
• And that’s all! Hurray!
• NOTE: If you have VS 2008 or newer, IntelliSense shows a bunch of
other methods: OrderBy(), Aggregate(), Count() and so much more,
all of them with this little blue arrow before them.
• These are LINQ methods allowing you to treat string as a collection and
perform querying. ‘Cause we haven’t talked about them, skip them.
They’re useful once you know much more about C# then you do now.
We’ll talk about them, don’t worry, in the 4th lesson.
C# 101, Lesson 2
• These methods also worth checking, but remember they create new
string, so if you use them often, consider StringBuilder.
Copyright © Vojtech Zicha
string – Other Methods
29
Usage
Comment
ToUpper()
boy.ToUpper();
Changes string to uppercase
ToLower()
boy.ToLower();
Changes string to lowercase
Trim()
boy.Trim();
Strips whitespace from b/e
IndexOf()
boy.IndexOf('g', 2);
Returns index of arg.
Contains()
boy.Contains('g');
Searches for arg.
Substring()
boy.Substring(2, 3);
Returns part of a string
Length
boy.Length;
Returns # of characters
Indexer
boy[2]
Returns spec. character
Replace()
boy.Replace('g', 'k'); Replaces 1st for 2nd arg.
StartsWith() boy.StartsWith("g");
Searches for arg. at the start
C# 101, Lesson 2
Name
Copyright © Vojtech Zicha
string - Recapitulation
30
C++
PHP
ToUpper()
mb_strtoupper()
ToLower()
mb_strtolower()
Trim()
trim()
IndexOf()
mb_strpos()
Contains()
mb_strpos()
Substring()
mb_substr()
Length
mb_strlen()
[]
[]
[]
Replace()
str_replace()
EndsWith()
-
StringBuilder
no need
Java
-
C and C++ in this variant does not handle Unicode; C#, PHP and Java does.
C# 101, Lesson 2
C (char*)
Copyright © Vojtech Zicha
C#
31
•
•
•
•
•
\n means new line (you can’t span more lines by string)
\t means tab
\" means " (without backslash it ends string)
\' means ' (available only in char literal '\'')
\\ means backslash
• Thinking about the last line? It’s there, because this is syntax
error:
"a\hj"
• If you want to write these 4 characters on screen, do:
"a\\hj“ // a backslash h j
C# 101, Lesson 2
• C# supports escape sequences – a way how to write a special
character to string. Here are two most convenient:
Copyright © Vojtech Zicha
string – Escape Sequences
32
@"a\f\d\fd\f\asdf\sadf\as\dfs\df\dfer\g"
• Easy and convenient.
C# 101, Lesson 2
• Imagine you want to write following on the screen:
a\f\d\fd\f\asdf\sadf\as\dfs\df\dfer\g
• That would be a lot of escaping, but you can avoid it using
special syntax: string starting by @ can span more lines
and it does not care about escape sequences.
Copyright © Vojtech Zicha
string – Escape Sequences
33
• But stop now. Go back.
• Try more examples. Be sure you know how these methods
work.
• Are you sure? Really? Let’s move on!
C# 101, Lesson 2
• Whoa, you’re fast.
Copyright © Vojtech Zicha
string
34
• C/C++ programmers, forget about your arrays. Forget about
pointers to the first item of array, creating on the heap, pointer
arithmetic, offset operator, forget about all of that. C# arrays are
automated, with a much higher level of abstraction.
• PHP programmers, forget about your arrays. What you have is so
dynamic, it’s more like a hash table on steroids. In C# there are
normal arrays. Your structures are more like collections we will
cover later.
• Later, we will cover collections – let’s say more powerful arrays.
So why to teach arrays at all? Because once your performance
matters, array are the fastest of all collections. But in all other
cases we prefer collections like lists or dictionaries.
• Now, don’t waste time, let’s start!
C# 101, Lesson 2
• Before we start, a few notes:
Copyright © Vojtech Zicha
Arrays
35
• If you don’t know the number, you can’t do much now. Later we
will cover collections which don’t have this limitation. But
remember – down there in you RAM memory, it’s always better to
know the number of elements at start. It’s just faster.
C# 101, Lesson 2
• For now, you used only single variables – like boy, x, or det. But
what if you want to store ten boys’ names? Well, you can have 10
variables, but that’s not cool.
• Arrays are way how to store more information under one name.
• Remember – when creating arrays, you have to know, how many
elements you want to store. This number is later unchangeable.
Copyright © Vojtech Zicha
Arrays
36
var array = new int[6]; Create an array of integers,
which will have 6 elements.
array[0] = 3;
array[1] = 6;
To 1st element store 3.
array[2] = 9;
To 4th element store 2.
array[3] = 2;
array[4] = 5;
array[5] = 8;
C# 101, Lesson 2
• See this code:
Copyright © Vojtech Zicha
Arrays
37
• If you tried to access [6], it would crash – raise an error. Later we’ll
learn how to catch these errors and prevent crashing of our
program.
• Remember: All items in array have to be of the same type.
• At start we used var, cause it’s shorter. If you don’t like it, you can
replace the code with following line – they’re the same (the array
type is always the type of items followed by [] without number):
int[] array = new int[6];
C# 101, Lesson 2
• When creating array, you specify its length – the number of
elements. In our example, 6. Then you can access indexes (using
familiar syntax with [ and ]) from 0 to 5 – six number.
Copyright © Vojtech Zicha
Arrays
38
• Is it possible? Think about it, you know how to do it.
• YES, the answer is object. You can store anything in an object.
var objArr = new object[3];
objArr[0] = 3;
objArr[1] = 2;
objArr[2] = "john";
C# 101, Lesson 2
• We said that you in array you can have items of only one type. But
what if you want to have there integers and strings together?
Copyright © Vojtech Zicha
Arrays
39
int ans = array[0] + array[4] * array[2];
Console.WriteLine(ans);
• This code outputs 48. Do you have it? Good.
• Then try this code, it won’t work.
• Remember what we said. You cannot multiply objects.
int ans2 = objArr[0] * objArr[1];
Console.WriteLine(ans2);
C# 101, Lesson 2
• How to use array? It’s easy, put this after your definitions of
both arrays:
Copyright © Vojtech Zicha
Arrays
40
• Reminder: use object’s ToString() method.
• You know how to convert strings to numbers.
• Reminder: use the int.Parse() or double.Parse() method.
• But in other cases, you have to use so called casting.
• Let’s see it on the next slide.
• NOTE: C programmers, forget about your casting, this is
much less powerful. You can cast only to the type name,
nothing more’s allowed, even void’s denied.
C# 101, Lesson 2
• Now it’s the time to learn how to convert type to type.
• You already know how to convert anything to string.
Copyright © Vojtech Zicha
Converting
41
object i = 5;
int j = (int)i;
• You can convert object into integer if and only if the object
already contains integer.
• You do that by writing the end type’s name between
parenthesis and before the variable name.
• If the object contained string, this code would fail.
C# 101, Lesson 2
• So, to cast object to integer:
Copyright © Vojtech Zicha
Casting
42
int ans2 = (int)objArr[0] + (int)objArr[1];
Console.WriteLine(ans2);
• Remember, that you shouldn’t use (string), there’s no
reason. Always prefer ToString() method – works better.
• Now you know how useful can object be! You just have to
remember, what to cast it on.
• We’ll discus object and casting more in the next lesson.
C# 101, Lesson 2
• Back to our object array, this is the working version:
Copyright © Vojtech Zicha
Arrays
43
array.Length; // 6
• NOTE for C/C++/PHP coders: Now we’ll speak about
multidimensional arrays. You don’t have them – you use jagged
arrays (arrays-of-arrays) instead. In C# you can use them, but we
much prefer built-in multidimensional array support.
• NOTE for Java coders: You know what I speak about, right? In C#
it works the same, it’s just named differently.
C# 101, Lesson 2
• To know how many elements is in the onedimensional array, use
Length property – works the same way as with strings:
Copyright © Vojtech Zicha
Arrays
44
• Which of these two fors will be faster (array has 10 elements)?
for (int i = 0; i < 10; i++)
{
// something
}
for (int i = 0; i < array.Length; i++)
{
// something
}
• The correct answer is – there’s no difference. Compiler does such an awesome job at
optimization that they’ll run with the same IL (assembler) code.
• So conclusion – always use the second variant, it’s more readable and has same
performance.
C# 101, Lesson 2
• NOTE if you used another programming language:
Copyright © Vojtech Zicha
Arrays – Advanced Note
45
var matrix =
matrix[0, 0]
matrix[0, 1]
matrix[1, 0]
matrix[1, 1]
matrix[2, 0]
matrix[2, 1]
new int[3, 2]; // the same as int[,] matrix =
= 2;
= -2;
= 1;
= 3;
= 0;
= 4;
• Pretty straightforward, isn’t it? Remember to use comma to separate dimensions.
C# 101, Lesson 2
2 −2
• Do you know matrices? Such as 1 3 ? How would you represent them in C#? No
0 4
worry, the language supports them.
• So let’s create and initialize our array:
Copyright © Vojtech Zicha
Two-dimensional Arrays
46
Console.WriteLine(matrix.Length);
• Remember, in multidimensional array Length property returns
the number of elements in total. It sums through all dimensions.
In our cases, it returns 6.
• If you want number of elements in specified dimension, you can
use the GetLength() method:
Console.WriteLine(matrix.GetLength(0)); // 3
Console.WriteLine(matrix.GetLength(1)); // 2
C# 101, Lesson 2
• Now we have a problem with lengths. How many items is in the
array? Let’s try this:
Copyright © Vojtech Zicha
Two-dimensional Arrays
47
var cube =
cube[0, 0,
cube[0, 0,
cube[0, 1,
cube[0, 1,
cube[1, 0,
cube[1, 0,
cube[1, 1,
cube[1, 1,
new int[2, 2, 2]; // same as int[,,] =
0] = 2;
1] = -2;
0] = 2;
1] = -2;
0] = 2;
1] = -2;
0] = 2;
1] = -2;
C# 101, Lesson 2
• All we said about two-dimensional arrays is true also for
multidimensional arrays – with three or even more dimensions.
Copyright © Vojtech Zicha
Multidimensional Arrays
48
• These two codes do the same.
var arr1 = new int[] { 0, 1, 2 };
var arr2 = new int[3];
arr2[0] = 0;
arr2[1] = 1;
arr2[2] = 2;
• NOTE: When using array initialization, you can omit the number
of elements in array. It will be set by the compiler to the number
of elements in the initialization.
You don’t have to omit this number.
C# 101, Lesson 2
• Our arrays examples weren’t nice – actually they were long. You
can save lines by initializing arrays on the line.
Copyright © Vojtech Zicha
Arrays - initialization
49
• The omitting of numbers works the same as in 1D arrays.
var matrix = new int[,] {
{ 2, -2 }, { 1, 3 }, { 0, 4 }
};
C# 101, Lesson 2
• This of course works for the multidimensional arrays – see
this code and compare to our previous definition of matrix:
Copyright © Vojtech Zicha
Arrays - initialization
50
var array = new int[] { 3, 6, 9, 2, 5, 8 };
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("At index {0} element
{1}", i, array[i]);
}
• If you’re not sure, what this code does, RUN IT. It’s not hard.
• To make this very common task easier, C# offers foreach construct.
C# 101, Lesson 2
• You probably figured out how to write all elements of array, probably
using for cycle. I’d do it like that:
Copyright © Vojtech Zicha
foreach
51
So the same code using foreach looks like this:
var array = new int[] { 3, 6, 9, 2, 5, 8 };
foreach (var element in array)
{
Console.WriteLine("Element {0}", element);
}
•
You have to specify a variable. Foreach is going to run the block as many times as number of items in array.
Each item is going to be stored in the provided variable.
•
•
•
•
NOTE: You can’t get a index of such an element in foreach. If you need it, you can use for as shown on previous
slide.
This method works also for multidimensional arrays. Try it.
You cannot change the value of element using this method – you can just read it.
NOTE: The advantage of foreach is, that it does not work only for arrays, but also for a lot of other structures
called “enumerable objects” (PHP/Java coders: the same as your iterable objects). So (if you know these terms)
SQL queries, XML files, collections, all of that uses foreach. That’s why it’s preferred way to run through array – it
can run through anything.
C# 101, Lesson 2
•
Copyright © Vojtech Zicha
foreach
52
• NOTE: Don’t use LINQ (if you know it). It’s much easier with
LINQ, in practice you’d use LINQ, but for this lesson, stick with
the old method of counting sum and average.
• GO!
• (Really, try it.)
C# 101, Lesson 2
• Ask user for 10 integers. Store them in array. After that
calculate sum and average.
Copyright © Vojtech Zicha
Ex. 2: Statistics
53
int sum = 0;
foreach (var el in array)
{
sum += el;
}
double average = (double)sum / array.Length;
Console.WriteLine("Sum: {0}, Average: {1}", sum, average);
Copyright © Vojtech Zicha
for (int i = 0; i < array.Length; i++)
{
Console.Write("Write: ");
var str = Console.ReadLine();
array[i] = int.Parse(str);
}
C# 101, Lesson 2
var array = new int[10];
54
• C# in default performs the integer division using integers (3/2
= 1, not 1.5). To force C# to do normal division, use the casting
(see my solution).
• Foreach can’t change values in array, so in the first cycle
(putting variables inside an array) I had to use the for cycle.
C# 101, Lesson 2
• NOTES
Copyright © Vojtech Zicha
Ex. 2: Statistics
55
var str = "myGod"; // same as string str = ...
foreach (var ch in str) // same as char ch in ...
{
Console.WriteLine(ch);
}
C# 101, Lesson 2
• We said that foreach works with so called enumerable objects.
For know we knew that arrays are enumerable.
• We also know another enumerable object – string.
• This codes enumerates (= goes through) each character in string –
try to RUN IT and examine the results.
Copyright © Vojtech Zicha
foreach and strings
56
C# 101, Lesson 2
• Wow, you covered strings and arrays. Numbers should be
easy, right? They’re not so, but definitely easier than strings
and arrays.
• So far we know integers (int) and real numbers (double),
but that’s not all.
• We have more types of numbers – they have different type
name and different suffix – let’s see them on the next slide
Copyright © Vojtech Zicha
Numbers
57
Range
Size
Usage
sbyte
integral
-128 to 127
Signed 8-bit integer
10
byte
integral
0 to 255
Unsigned 8-bit integer
10
short
integral
-32,768 to 32,767
Signed 16-bit integer
10
ushort
integral
0 to 65,535
Unsigned 16-bit integer
10U
int
integral
2,147,483,648 to
2,147,483,647
Signed 32-bit integer
10
uint
integral
0 to 4,294,967,295
Unsigned 32-bit integer
10U
long
integral
app. -9*10^18 to
9*10^18
Signed 64-bit integer
10L
ulong
integral
app. 0 to 18*10^18
Unsigned 64-bit integer
10UL
float
floating point
±1.5e−45 to ±3.4e38
Precision: 8 digits
1.53F
double
floating point
±5.0e−324 to
±1.7e308
Precision: 15-16 digits
1.53
Different Number types
C# 101, Lesson 2
Description
Copyright © Vojtech
Zicha
Type name
58
var k = 0XAL; // you store 10; k is long
• Remember the suffixes for proper usage of numbers.
float f1 = 1.25; // syntax error
float f2 = 1.25f; // correct
• The types smaller than int are very rarely used. The most
efficient are int (uint) and long (ulong).
• This difference comes from the way how RAM works.
C# 101, Lesson 2
• You can write numbers in hexadecimal format:
Copyright © Vojtech Zicha
Numbers
59
• They round themselves a lot and produce unexpected results.
• If you want to know more, try to look for CS Numeric courses.
• The only precise types are the integer ones.
• But when you work with the money, you have to be precise
but still work with the decimal parts.
• That’s why there’s special type for precise decimal
operations – it is called decimal.
C# 101, Lesson 2
• float and double numbers have a problem – they’re not
precise.
Copyright © Vojtech Zicha
Real numbers
60
decimal amount = 1.23m;
• NEVER store money amounts in double or float. That’s just
nonsense.
Copyright © Vojtech Zicha
• You can work with decimals very same way as with other
number types.
C# 101, Lesson 2
decimal
• But also remember that decimal takes 128 bits of memory
– 4 times the amount of float.
61
• Its suffix is M.
• Remember that decimal is precise.
short a = 3;
int b = a;
long c = b;
float d = c;
double e = d;
• This is called implicit casting – it happens without any keyword.
When you use implicit casting, you don’t loose anything – the value
won’t change.
C# 101, Lesson 2
• You can cast smaller numeric type to larger numeric type without
any notation. You can also cast freely the integer to any real number
type.
Copyright © Vojtech Zicha
Casting Numbers
62
double f = 300000000000.3;
float g = (float)f;
long h = (long)g; // 29999995664
int i = (int)h;
short j = (short)i; // -32768
C# 101, Lesson 2
• You can also cast to other combination (larger to smaller, real to
integer), but know there’s a risk. You can get nonsense
information or lost some parts of it.
• C# compiler won’t let you do that – he cares about you, but if you
really want it, you can use explicit casting the way I’ve already
shown you.
Copyright © Vojtech Zicha
Casting Numbers
63
• +,-,*,/,% (modulo)
• ==, !=, <, >
• and more
• Easy, right?
C# 101, Lesson 2
• With numbers you can do following operations
Copyright © Vojtech Zicha
Operations with Numbers
64
0101 (5)
& 0011 (3)
-----0001 (1)
0101 (5)
| 0011 (3)
-----0111 (7)
0101 (5)
^ 0011 (3)
-----0110 (6)
C# 101, Lesson 2
• C# supports bitwise operations.
• We’ll be concerned about AND (&), OR (|), and XOR(^)
Copyright © Vojtech Zicha
Bitwise Operations
65
bool tr = true;
bool fa = false;
• That’s all. Usually.
C# 101, Lesson 2
• Boolean is the most boring of all types. It can contain only
two possible values – true or false.
Copyright © Vojtech Zicha
Boolean
66
bool
bool
bool
bool
active = true;
tall = false;
blond = true;
doable = true;
• How many bites of memory would this use? If you think 4 (4 zeros or
ones), you’re not right. Its 128 or 256 bits depending on your
computer.
• Compiler puts variable in 32- (or 64-) bit-blocks even if it’s
smaller. It’s faster for him. That’s also why smaller than int
variables are usually useless – they will always take 32 or 64 bits –
you just wouldn’t be able to use them.
C# 101, Lesson 2
• Suppose you want to store, if your student is Active or not, Tall or
not, Blond or not and Doable or not.
• You could use 4 boolean variables.
Copyright © Vojtech Zicha
Bitwise Flag Enumeration
67
• But how to use it? We can use bitwise operation –that’s
why this technique is called bitwise flag enumeration.
C# 101, Lesson 2
• So some smart guys figured it out. You can use bits directly
to store boolean information. Think that 1st bit would be
active, 2nd tall and so on. So our guy/girl from previous
slide might look like this: 1101.
(The convention is start from the last number,
the MSB if you know what I mean.)
Copyright © Vojtech Zicha
Bitwise Flag Enumeration
68
before
we add
0010
| 0100
-----after with
0110
before
we remove
after without
0110
^ 0100
-----0010
C# 101, Lesson 2
• To add a feature to our guy/girl, we can use operation OR.
• To remove a feature from our guy/girl, we use XOR.
Copyright © Vojtech Zicha
Bitwise Flag Enumeration
69
our guy
does he have
result
0110
& 0001
-----0000
0111
& 0001
-----0001
• If the result is anything else then 0, he/she is doable. If it is 0,
he/she is worth nothing, sorry, is not doable.
C# 101, Lesson 2
• To ask, “Is he/she doable?” we can use AND operation
Copyright © Vojtech Zicha
Bitwise Flag Enumeration
• Sorry, for this joke. I just like it.
• In most languages, you would now use integers to store these
features. But C# has built-in support, so you just don’t care.
70
•
Put this code before your class Program, but inside your namespace Ex1.
[Flags]
enum Student
{
None = 0,
Active = 0x1,
Tall = 0x2,
Blond = 0x4,
Doable = 0x8
}
• Now you have defined a new type – Student. It can be Nothing (zero), active, tall, blond
and/or doable. Remember that for values (after =) you have to use the powers of two.
You can use hexadecimal or decimal system – I prefer the first one, it’s similar to binary
system. You can put there as much items as you want.
C# 101, Lesson 2
• So, let’s define our enumeration. Be careful, it has to be exactly like that (you can just change
names).
Copyright © Vojtech Zicha
Bitwise Flag Enumeration
71
• This code will be inside your Main function, as you’re used to.
Student jamie = Student.Active | Student.Blond
| Student.Doable;
• Now let’s ask, is Jamie blond and is Jamie tall?
• Try to remember this syntax, it’s always the same. You can put it
on one line, I just don’t have space here.
bool isBlond = (jamie & Student.Blond) ==
Student.Blond; // true
bool isTall = (jamie & Student.Tall) ==
Student.Tall; // false
C# 101, Lesson 2
• Now let’s you our type. Let’s have a Jamie, who’s active, blond and
doable, but definitely not tall.
Copyright © Vojtech Zicha
Bitwise Flag Enumeration
72
C# 101, Lesson 2
• We met several places where conditions are used – if, while, for
and so on.
• Remember, in conditions you can only use such expressions
(code returning something) that are boolean.
• Consider this code: if (3 % 2) // something. It is syntax
error. 3 % 2 returns 1, but that is not boolean. You have to correct
it to this: if ((3 % 2) == 1) // something.
• NOTE: I know, C/C++/PHP/etc. coders, in your language it’s
working. But this is C#, it requires boolean in conditions, so
don’t forget to write there these equals.
Copyright © Vojtech Zicha
NOTE about Booleans and Conditions
73
• We have other types available in .NET framework for us, so let’s
go through them. This is in stock for us:
•
•
•
•
Regular Expressions
Manipulation with files and folders
Networking
Introduction to Graphics – usage of Vector and Matrix classes
C# 101, Lesson 2
• You’ve covered all basic types, congratulations. It wasn’t that
hard, was it?
• But unfortunately that’s not the end of things.
• I know, 73 slides were too many, but we have still topics
to go through.
Copyright © Vojtech Zicha
Midterm Recapitulation
74
C# 101, Lesson 2
• Now, we’re going to discover what’s in stock for us in
.NET Framework. There’s no way using C# without .NET*.
• .NET Framework is object-oriented framework, it means
it heavily uses classes and objects.
• On the next slide, we’ll quickly go through not, what it
means, but how to use it. Next lesson, we’ll dive deep into
it.
Copyright © Vojtech Zicha
Classes and Objects
75
•
* There’s a WinRT C# in Windows 8 / Windows on ARM, but who knows how that’s going to work.
int.Parse("3");
C# 101, Lesson 2
• Remember StringBuilder? That’s a class. Class is something
containing other useful thinks. One of them are static
methods. If we say “call static method” it means write
name of the class, write dot and write a name of method
followed by arguments, etc.
• Example? Converting strings to numbers (think for now,
that ‘int’ is a name of a class – it kind of is)
Copyright © Vojtech Zicha
Classes and Objects
76
var sb = new StringBuilder();
• We do it by writing new, then a name of a class followed by
parenthesis with arguments. We have to store this object in
variable. For know, always use var.
• When we have object, we can call instance methods – methods
of the object, for example:
sb.Append("hi");
• It is similar to calling static methods, but instead of name of a
class, we put the variable where we have our object. We used this
principle a lot with strings, for example boy.ToUpper().
C# 101, Lesson 2
• But we can also create an object of a class. Remember string
builder:
Copyright © Vojtech Zicha
Classes and Objects
77
C# 101, Lesson 2
• Expecting a list of classes and methods? No, not yet. We will
start by learning another coding language.
• WHAT???
• Yeah, we do have to.
• Regular Expression are way, how to tell, that string has
some format – it is digit, email address, URI or something
like that.
• They are hard, cryptic, but the best tool we have today.
• Here, I’ll teach you just the very basics, but I encourage you
to learn more on your own.
Copyright © Vojtech Zicha
Regular Expressions
78
• For example, you can have a mask “email address”, then get
something from your user, compare it to the mask and say “it’s
valid” or “it’s wrong”. That’s how the website do it – using
regular expressions (mostly).
• The easiest mask is just a string – it matches when the
string contains the mask.
• NOTE: Pay attention, every character in mask has some
meaning, you can’t even put there space – it would change the
meaning of mask.
C# 101, Lesson 2
• Regular expressions are kind of mask. You write this mask,
then you take a string and ask: “Does it match my mask?”
Copyright © Vojtech Zicha
Regular Expressions
79
• Valid: oabce, a abc e, abc
• Invalid: ab c, oacbe
• Now we’ll use modifiers. ^ means: “here the string starts”.
• EXAMPLE: Mask ^abc
• Valid: abc, abcefg, abc ef
• Invalid: oabce, a abce, ab ce
• Another modifier. $ means: “here the string ends”.
• EXAMPLE: Mask abc$
• Valid: abc, efgabc, ef abc
• Invalid: abce, eabc e, e ab c
C# 101, Lesson 2
• EXAMPLE: Mask abc
Copyright © Vojtech Zicha
Regular Expressions
80
• \b matches a word boundary
• If you want to match any word staring with n, this is the mask
• \bn (aka word boundary / new word followed by n)
• \w matches any word character
• So if you want to match any word with second letter n:
• \b\wn (aka word boundary, any letter inside of a word and n)
• \s matches any whitespace (space, tab, new line, …)
• So if you want to match any whitespace followed by any character:
• \s\w
• \d matches any digit
• So if you want to match 4digit PIN with hyphen in the middle:
• \d\d-\d\d
C# 101, Lesson 2
• Another set of modifiers:
Copyright © Vojtech Zicha
Regular Expressions
81
• So if you want to match exactly digit or empty string:
• ^\d?$ (if you’d omit ^ and $, it’d look for nothing or digit, so it’d always match)
• * means, that previous character can be there 0 and more times
• So if you want to match exactly a letter followed by any number of digits (even
none):
• ^\w\d*$
• + means, that previous character can be there 1 and more times
• So if you want to match text containing email without dots:
• \w+@\w+
• {n} means, that previous character has to be there n times
• So only 4 digits: ^\d{4}$
• {n,m} means, that previous character can be there from n to m times
• So from 3 to 5 digits preceded by optional minus: ^-?\d{3,5}$
C# 101, Lesson 2
• ? means, that previous character can be there 0 or 1 times
Copyright © Vojtech Zicha
Regular Expressions
82
• [ ] determines, that any character put inside can be at this location
• NOTE: inside [ ] instead of – you have to use \• So from 3 to 5 digits preceded by optional minus or plus
^[\-+]?\d{3,5}$
• You can specify range inside [ ] by using hyphen
• So from 3 to 5 digits preceded by optional minus or plus and followed by any count of
required number from 0 to 5:
•
^[\-+]?\d{3,5}[0-5]*$
• If you start [ ] with ^, it means “anything except”
• So to match naïve email address (you can’t just write . to match . (. means any character),
you have to use \.):
•
•
•
^[^@]+@[^@\.]+\.\w+$
String has to start with anything except of @ at least 1 time; then @; then anything except of
dot and @ at least 1 time; then dot; then any word character at least 1 time; and then end.
Don’t use this at production! It’s really naïve expression. (For example email
spam+me@sub.domain.com fails, but is valid. g a d@me.com (with spaces) passes, but is
invalid.)
Copyright © Vojtech Zicha
•
C# 101, Lesson 2
Regular Expressions
83
@"^[^@]+@[^@\.]+\.\w+$"
C# 101, Lesson 2
• And that’s all for basics. Once again, I encourage you to
learn all other syntax – it’s really powerful tool.
• Also try to look for examples, get a little practice.
• And when you know how to write a mask, let’s learn how to
use it in .NET and C#.
• In C# you’ll write mask into a string. But remember escape
sequences! You’d be backslashing all day. That’s why we
nearly always use @-string syntax with reg. ex. masks:
Copyright © Vojtech Zicha
Regular Expressions in .NET
84
var email = Console.ReadLine();
var mask = @"^[^@]+\@[^@\.]+\.\w+$";
if (Regex.IsMatch(email, mask))
{
Console.WriteLine("It is valid email.");
}
else
{
Console.WriteLine("It's not a valid email.");
}
• TRY IT.
C# 101, Lesson 2
• Expecting something hard? No, it’s not. This code checks whether email is
valid.
Copyright © Vojtech Zicha
Regular Expressions in .NET
85
using System.Text.RegularExpressions;
• Now RUN IT. It works (at least for me :-)
• It uses a static method IsMatch of class Regex (see code).
• The method returns true, if the 1st argument matches the
mask provided in the 2nd argument.
• And that’s all. The biggest work is to come up with the
correct and working and perfect mask.
C# 101, Lesson 2
• Error? Does it work? It doesn’t. You haven’t told compiler
you’re about to use regular expressions. So after your 4
obligate usings put this one:
Copyright © Vojtech Zicha
Regular Expressions in .NET
86
•
•
•
•
•
Search for the parts of the document
Examine groups of text in the string
Replace parts of the string by something other
Making assertions about the code validating future characters
Quoting parts of the string
• But I’ll let those topics for you. If you find yourself dealing
with a text, dive into regexes (regular expressions) and
they might provide answer.
C# 101, Lesson 2
• That’s not all you can do with regular expressions:
Copyright © Vojtech Zicha
Regular Expressions in .NET
87
using System.IO;
• It has two main parts we’ll cover:
• Working with whole folders and files (renaming, moving,
removing, enumerating)
• Working with the content of a file (creating, reading, writing, etc.)
C# 101, Lesson 2
• Now we are at the second topic. Once again, we’ll cover just the
basics of it, the rest is upon you.
• File and Folder Manipulation is sometimes called Input / Output
Operations. For them to work, you have to use this using:
Copyright © Vojtech Zicha
File and Folder Manipulation
88
• DO IT. No, I’m kidding. I’ll guide you through.
C# 101, Lesson 2
• Write a program, that will write all folders and files inside a
specified path by user.
Copyright © Vojtech Zicha
Ex. 3: Content of a Folder
89
• At first we have to get a path to folder, user wants to see.
• Now we have to get a list of dictionaries. Method we look
for is static method of Directory class called
EnumerateDirectories() taking 1 argument: the path. By
the name you can guess, that it returns something for the
foreach cycle – the cycle for enumerations.
Copyright © Vojtech Zicha
var path = Console.ReadLine();
C# 101, Lesson 2
Ex. 3: Content of a Folder
var e = Directory.EnumerateDirectories(path);
90
foreach (var dir in e)
{
Console.WriteLine("{0}\t\tdir", dir);
}
• Now focus on the files. We can use the same principle, but
using the EnumerateFiles() method. Try it yourself.
C# 101, Lesson 2
• Once we have a result, we can use foreach. We will get a
string containing a name of folder.
Copyright © Vojtech Zicha
Ex. 3: Content of a Folder
91
var path = Console.ReadLine();
var e = Directory.EnumerateDirectories(path);
foreach (var dir in e)
{
Console.WriteLine("{0}\t\tdir", dir);
}
e = Directory.EnumerateFiles(path);
foreach (var file in e)
{
Console.WriteLine("{0}\t\tfile", file);
}
My output
Copyright © Vojtech
Zicha
Final code
C# 101, Lesson 2
Ex. 3: Content of a folder
92
• OK, let’s go.
C# 101, Lesson 2
• Write a program, that will rename a file inside specified
path to a new name. User will specify the new name
without extension, that will remain the same.
Copyright © Vojtech Zicha
Ex. 4: Renaming a File
93
var path = Console.ReadLine();
var oldName = Console.ReadLine();
var newName = Console.ReadLine();
• In .NET IO you cannot “rename” file. What you actually will
do is you move the first file to a new one. To be able to do
so, you need two paths – original one and new one.
C# 101, Lesson 2
• User has to specify three things: path, old name with
extension and new name without extension.
Copyright © Vojtech Zicha
Ex. 4: Renaming a File
94
var oldPath = Path.Combine(path, oldName);
• Now we have to get a new path. But we miss the extension in the
name of new file, we have to extract that from the name of old file.
To do so, we can use the static method GetExtension() of a Path
class.
var ext = Path.GetExtension(oldPath);
• Now we have to combine all to form an new path.
var newPath = Path.Combine(path, newName + ext);
C# 101, Lesson 2
• So we have to get an old path – we can use static method
Combine() of a Path class.
Copyright © Vojtech Zicha
Ex. 4: Renaming a File
95
File.Move(oldPath, newPath);
• So the resulting code is pretty straight-forward:
var path = Console.ReadLine();
var oldName = Console.ReadLine();
var newName = Console.ReadLine();
var oldPath = Path.Combine(path, oldName);
var ext = Path.GetExtension(oldPath);
var newPath = Path.Combine(path, newName + ext);
File.Move(oldPath, newPath);
C# 101, Lesson 2
• Once we have both paths it’s easy – just use static method Move of a File class.
Copyright © Vojtech Zicha
Ex. 4: Renaming a File
96
• File (and also FileInfo)
• Directory (and also DirectoryInfo)
• Path (but no PathInfo)
• Now, we’ll move to the second part – manipulating the
contents of a file.
C# 101, Lesson 2
• Look at MSDN to learn more about these 3 important
classes:
Copyright © Vojtech Zicha
File and Folder Manipulation
97
• In .NET, we use streams to read/write, so you open a stream to a
file.
• Streams are only one-way at the time, you can either read from it
or write to it, not both at the same time.
• To write to a stream, we use StreamWriter.
• To read from a stream, we use StreamReader.
• When you open a file, you have to make sure you close it.
• But that’s a problem. What if you open a file and that happens
some error? What to do know? The file would remain open.
• But don’t worry, we have a solution to this.
C# 101, Lesson 2
• Before you can read or write from/to a file, you have to open it.
Copyright © Vojtech Zicha
File Contents Manipulation
98
• Once again, I’ll guide you through.
C# 101, Lesson 2
• Write to a file specified by user a Adolf Hitler’s definition of
politics.
Copyright © Vojtech Zicha
Ex. 5: Writing to a File
99
var path = Console.ReadLine();
• And then we can start by opening file for writing. How to do so?
Call static method OpenWrite() of class File. This method takes
path as an argument and returns file stream.
var stream = File.OpenWrite(path);
• Now create a StremWriter object.
var writer = new StreamWriter(stream);
• And write!
writer.WriteLine("A.
• And that is all!
C# 101, Lesson 2
• At first, user has to specify the path to a file:
Copyright © Vojtech Zicha
Ex. 5: Writing to a File
Hitler: Politics is a fight of a power.");
100
• Using has two meaning – as a statements it imports some namespace (we’ve
already been using it), but as a block it takes care of “exception handling” –
what we need now.
using (var stream = File.OpenWrite(path))
{
var writer = new StreamWriter(stream);
writer.WriteLine("A. Hitler: Politics is a fight of
}
a power.");
• So whenever you have to make sure some object will be properly closed (in
.NET we call it disposed), use the using block as shown above.
• We’ll cover that in more detail in our OOP lessons.
C# 101, Lesson 2
• But what if there’d be some error? We could leave stream open for a large
period of a time. To solve this problem, we can use using block.
Copyright © Vojtech Zicha
Ex. 5: Writing a File
101
var path = Console.ReadLine();
using (var stream = File.OpenRead(path))
{
var reader = new StreamReader(stream);
var wholeFile = reader.ReadToEnd();
var line = reader.ReadLine();
}
C# 101, Lesson 2
• Reading a file can be very easy – the code is similar to one used for a
writing.
Copyright © Vojtech Zicha
Reading a File
102
• Downloading file can take a large amount of time. During that, our
application would be unresponsive. Nothing big when developing
Console application, but think about GUI. User would see the
Unresponsive window, OS would try to kill our app.
• We somehow have to manage to download a file on background.
C# 101, Lesson 2
• Now, to something more interesting. Networking
• There’s much to say about networking – you can spend weeks
trying to fully understand how it works.
• We’ll make our work as easy as possible. We’ll go through just the
simplest scenario possible: downloading a file over HTTP
protocol. Nothing easier is out there.
• But still, we have several problems:
Copyright © Vojtech Zicha
Network Manipulation
103
C# 101, Lesson 2
• So, the simplest scenario. We’ll require this using:
using System.Net;
• And store the path.
var path = "http://csharp101.zicha.name/index.html";
• Now let’s create our downloader, the WebClient object.
var downloader = new WebClient();
• Once we have it download our address and write it on
scren:
var str = downloader.DownloadString(path);
Console.WriteLine(str);
Copyright © Vojtech Zicha
HTTP Downloading
104
• To use this construct, you have to use C# 5.0 and at least Visual
Studio 11 Preview in Windows 8 Developer Preview
(at time of writing – January 2012)
• We’ll cover that in more depth later, for now let’s just see
the ideal solution. You can copy that and use it. How it
works, we’ll discuss at our OOP lectures.
C# 101, Lesson 2
• So far so good? But remember, the code waits for
downloading and does nothing. If in GUI, it is unresponsive.
• We’ll cover this problem using async-await construct.
Copyright © Vojtech Zicha
HTTP Downloading
105
C# 101, Lesson 2
static async void Main(string[] args)
{
var path = "http://csharp101.zicha.name/index.html";
var downloader = new WebClient();
var str = await
downloader.DownloadStringAsync(path);
Console.WriteLine(str);
}
• It wasn’t that hard, was it. And these two keywords and different
method make it responsive and fast.
Copyright © Vojtech Zicha
HTTP Downloading
106
C# 101, Lesson 2
Copyright © Vojtech
Zicha
Download at csharp101.zicha.name
C# 101, LESSON 3
107
Download