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

{

_price = price;

}

private decimal _price;

public decimal Price { get { return _price * (1 + vat); } }

}

Section 52.53: delegate

Delegates are types that represent a reference to a method. They are used for passing methods as arguments to other methods.

Delegates can hold static methods, instance methods, anonymous methods, or lambda expressions.

class DelegateExample

{

public void Run()

{

//using class method

InvokeDelegate( WriteToConsole );

//using anonymous method

DelegateInvoker di = delegate ( string input )

{

Console.WriteLine( string.Format( "di: {0} ", input ) ); return true;

};

InvokeDelegate( di );

//using lambda expression

InvokeDelegate( input => false );

}

public delegate bool DelegateInvoker( string input );

public void InvokeDelegate(DelegateInvoker func)

{

var ret = func( "hello world" );

Console.WriteLine( string.Format( " > delegate returned {0}", ret ) );

}

public bool WriteToConsole( string input )

{

Console.WriteLine( string.Format( "WriteToConsole: '{0}'", input ) ); return true;

}

}

When assigning a method to a delegate it is important to note that the method must have the same return type as well as parameters. This di ers from 'normal' method overloading, where only the parameters define the signature of the method.

Events are built on top of delegates.

Section 52.54: unchecked

The unchecked keyword prevents the compiler from checking for overflows/underflows.

GoalKicker.com – C# Notes for Professionals

271

For example:

const int ConstantMax = int.MaxValue; unchecked

{

int1 = 2147483647 + 10;

}

int1 = unchecked(ConstantMax + 10);

Without the unchecked keyword, neither of the two addition operations will compile.

When is this useful?

This is useful as it may help speed up calculations that definitely will not overflow since checking for overflow takes time, or when an overflow/underflow is desired behavior (for instance, when generating a hash code).

Section 52.55: ushort

A numeric type used to store 16-bit positive integers. ushort is an alias for System.UInt16, and takes up 2 bytes of memory.

Valid range is 0 to 65535.

ushort a =

50; //

50

ushort

b =

65536;

// Error, cannot be converted

ushort

c =

unchecked((ushort)65536); // Overflows (wraps around to 0)

 

 

 

 

Section 52.56: sizeof

Used to obtain the size in bytes for an unmanaged type

int byteSize = sizeof(byte) // 1 int sbyteSize = sizeof(sbyte) // 1 int shortSize = sizeof(short) // 2 int ushortSize = sizeof(ushort) // 2 int intSize = sizeof(int) // 4

int uintSize = sizeof(uint) // 4 int longSize = sizeof(long) // 8 int ulongSize = sizeof(ulong) // 8

int charSize = sizeof(char) // 2(Unicode) int floatSize = sizeof(float) // 4

int doubleSize = sizeof(double) // 8 int decimalSize = sizeof(decimal) // 16 int boolSize = sizeof(bool) // 1

Section 52.57: in

The in keyword has three uses:

a) As part of the syntax in a foreach statement or as part of the syntax in a LINQ query

foreach (var member in sequence)

{

// ...

}

GoalKicker.com – C# Notes for Professionals

272

b) In the context of generic interfaces and generic delegate types signifies contravariance for the type parameter in question:

public interface IComparer<in T>

{

// ...

}

c) In the context of LINQ query refers to the collection that is being queried

var query = from x in source select new { x.Name, x.ID, };

Section 52.58: implicit

The implicit keyword is used to overload a conversion operator. For example, you may declare a Fraction class that should automatically be converted to a double when needed, and that can be automatically converted from int:

class Fraction(int numerator, int denominator)

{

public int Numerator { get; } = numerator; public int Denominator { get; } = denominator;

// ...

public static implicit operator double(Fraction f)

{

return f.Numerator / (double) f.Denominator;

}

public static implicit operator Fraction(int i)

{

return new Fraction(i, 1);

}

}

Section 52.59: do

The do operator iterates over a block of code until a conditional query equals false. The do-while loop can also be interrupted by a goto, return, break or throw statement.

The syntax for the do keyword is:

do { code block; } while( condition );

Example:

int i = 0;

do

{

Console.WriteLine("Do is on loop number {0}.", i); } while (i++ < 5);

Output:

"Do is on loop number 1."

GoalKicker.com – C# Notes for Professionals

273

"Do is on loop number 2." "Do is on loop number 3." "Do is on loop number 4." "Do is on loop number 5."

Unlike the while loop, the do-while loop is Exit Controlled. This means that the do-while loop would execute its statements at least once, even if the condition fails the first time.

bool a = false;

do

{

Console.WriteLine("This will be printed once, even if a is false."); } while (a == true);

Section 52.60: long

The long keyword is used to represent signed 64-bit integers. It is an alias for the System.Int64 datatype present in mscorlib.dll, which is implicitly referenced by every C# project when you create them.

Any long variable can be declared both explicitly and implicitly:

long long1 = 9223372036854775806; // explicit declaration, long keyword used var long2 = -9223372036854775806L; // implicit declaration, 'L' suffix used

A long variable can hold any value from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, and can be useful in situations which a variable must hold a value that exceeds the bounds of what other variables (such as the int variable) can hold.

Section 52.61: enum

The enum keyword tells the compiler that this class inherits from the abstract class Enum, without the programmer having to explicitly inherit it. Enum is a descendant of ValueType, which is intended for use with distinct set of named constants.

public enum DaysOfWeek

{

Monday,

Tuesday,

}

You can optionally specify a specific value for each one (or some of them):

public enum NotableYear

{

EndOfWwI = 1918;

EnfOfWwII = 1945,

}

In this example I omitted a value for 0, this is usually a bad practice. An enum will always have a default value produced by explicit conversion (YourEnumType) 0, where YourEnumType is your declared enume type. Without a value of 0 defined, an enum will not have a defined value at initiation.

The default underlying type of enum is int, you can change the underlying type to any integral type including byte,

GoalKicker.com – C# Notes for Professionals

274