Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
57
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

Console.WriteLine("Starting a useless process..."); Stopwatch stopwatch = Stopwatch.StartNew();

int delay = await UselessProcessAsync(1000); stopwatch.Stop();

Console.WriteLine("A useless process took {0} milliseconds to execute.", stopwatch.ElapsedMilliseconds);

}

public async Task<int> UselessProcessAsync(int x)

{

await Task.Delay(x); return x;

}

Output:

"Starting a useless process..." **... 1 second delay... **

"A useless process took 1000 milliseconds to execute."

The keyword pairs async and await can be omitted if a Task or Task<T> returning method only returns a single asynchronous operation.

Rather than this:

public async Task PrintAndDelayAsync(string message, int delay)

{

Debug.WriteLine(message); await Task.Delay(x);

}

It is preferred to do this:

public Task PrintAndDelayAsync(string message, int delay)

{

Debug.WriteLine(message); return Task.Delay(x);

}

Version = 5.0

In C# 5.0 await cannot be used in catch and finally.

Version ≥ 6.0

With C# 6.0 await can be used in catch and finally.

Section 52.10: for

Syntax: for (initializer; condition; iterator)

The for loop is commonly used when the number of iterations is known.

The statements in the initializer section run only once, before you enter the loop.

The condition section contains a boolean expression that's evaluated at the end of every loop iteration to

GoalKicker.com – C# Notes for Professionals

234

determine whether the loop should exit or should run again.

The iterator section defines what happens after each iteration of the body of the loop.

This example shows how for can be used to iterate over the characters of a string:

string str = "Hello";

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

{

Console.WriteLine(str[i]);

}

Output:

H e l l o

Live Demo on .NET Fiddle

All of the expressions that define a for statement are optional; for example, the following statement is used to create an infinite loop:

for( ; ; )

{

// Your code here

}

The initializer section can contain multiple variables, so long as they are of the same type. The condition section can consist of any expression which can be evaluated to a bool. And the iterator section can perform multiple actions separated by comma:

string hello = "hello";

for (int i = 0, j = 1, k = 9; i < 3 && k > 0; i++, hello += i) { Console.WriteLine(hello);

}

Output:

hello hello1 hello12

Live Demo on .NET Fiddle

Section 52.11: abstract

A class marked with the keyword abstract cannot be instantiated.

A class must be marked as abstract if it contains abstract members or if it inherits abstract members that it doesn't implement. A class may be marked as abstract even if no abstract members are involved.

GoalKicker.com – C# Notes for Professionals

235

Abstract classes are usually used as base classes when some part of the implementation needs to be specified by another component.

abstract class Animal

{

string Name { get; set; }

public abstract void MakeSound();

}

public class Cat : Animal

{

public override void MakeSound()

{

Console.WriteLine("Meov meov");

}

}

public class Dog : Animal

{

public override void MakeSound()

{

Console.WriteLine("Bark bark");

}

}

Animal cat = new Cat(); cat.MakeSound();

Animal dog = new Dog(); dog.MakeSound();

//Allowed due to Cat deriving from Animal

//will print out "Meov meov"

//Allowed due to Dog deriving from Animal

//will print out "Bark bark"

Animal animal = new Animal(); // Not allowed due to being an abstract class

A method, property, or event marked with the keyword abstract indicates that the implementation for that member is expected to be provided in a subclass. As mentioned above, abstract members can only appear in abstract classes.

abstract class Animal

{

public abstract string Name { get; set; }

}

public class Cat : Animal

{

public override string Name { get; set; }

}

public class Dog : Animal

{

public override string Name { get; set; }

}

Section 52.12: fixed

The fixed statement fixes memory in one location. Objects in memory are usually moving arround, this makes garbage collection possible. But when we use unsafe pointers to memory addresses, that memory must not be moved.

We use the fixed statement to ensure that the garbage collector does not relocate the string data.

GoalKicker.com – C# Notes for Professionals

236

Fixed Variables

var myStr = "Hello world!";

fixed (char* ptr = myStr)

{

//myStr is now fixed (won't be [re]moved by the Garbage Collector).

//We can now do something with ptr.

}

Used in an unsafe context.

Fixed Array Size

unsafe struct Example

{

public fixed byte SomeField[8]; public fixed char AnotherField[64];

}

fixed can only be used on fields in a struct (must also be used in an unsafe context).

Section 52.13: default

For classes, interfaces, delegate, array, nullable (such as int?) and pointer types, default(TheType) returns null:

class MyClass {} Debug.Assert(default(MyClass) == null); Debug.Assert(default(string) == null);

For structs and enums, default(TheType) returns the same as new TheType():

struct Coordinates

{

public int X { get; set; } public int Y { get; set; }

}

struct MyStruct

{

public string Name { get; set; }

public Coordinates Location { get; set; } public Coordinates? SecondLocation { get; set; } public TimeSpan Duration { get; set; }

}

var defaultStruct = default(MyStruct); Debug.Assert(defaultStruct.Equals(new MyStruct())); Debug.Assert(defaultStruct.Location.Equals(new Coordinates())); Debug.Assert(defaultStruct.Location.X == 0); Debug.Assert(defaultStruct.Location.Y == 0); Debug.Assert(defaultStruct.SecondLocation == null); Debug.Assert(defaultStruct.Name == null); Debug.Assert(defaultStruct.Duration == TimeSpan.Zero);

default(T) can be particularly useful when T is a generic parameter for which no constraint is present to decide

whether T is a reference type or a value type, for example:

GoalKicker.com – C# Notes for Professionals

237