13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>C#</strong> LANGUAGE SPECIFICATIONAn interesting and useful property of a delegate instance is that it does not know or care about the classes ofthe methods it encapsulates; all that matters is that those methods be compatible (§22.1) with the delegate’stype. This makes delegates perfectly suited for “anonymous” invocation. This is a powerful capability.There are three steps in defining and using delegates: declaration, instantiation, and invocation. Delegatesare declared using delegate declaration syntax. The exampledelegate void SimpleDelegate();declares a delegate named SimpleDelegate that takes no arguments and returns no result.The exampleclass Test{static void F() {System.Console.WriteLine("Test.F");}static void Main() {SimpleDelegate d = new SimpleDelegate(F);d();}}creates a SimpleDelegate instance and then immediately calls it.There is not much point in instantiating a delegate for a method and then immediately calling that methodvia the delegate, as it would be simpler to call the method directly. Delegates really show their usefulnesswhen their anonymity is used. The examplevoid MultiCall(SimpleDelegate d, int count) {for (int i = 0; i < count; i++) {d();}}shows a MultiCall method that repeatedly calls a SimpleDelegate. The MultiCall method doesn’tknow or care about the type of the target method for the SimpleDelegate, what accessibility that methodhas, or whether or not that method is static. All that matters is that the target method is compatible (§22.1)with SimpleDelegate.8.11 EnumsAn enum type declaration defines a type name for a related group of symbolic constants. Enums are used for“multiple choice” scenarios, in which a runtime decision is made from a fixed number of choices that areknown at compile-time.The exampleenum Color{Red,Blue,Green}class Shape{public void Fill(Color color) {switch(color) {case Color.Red:…break;case Color.Blue:…break;44

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!