Bluffer's Guide to C #2

Source: Internet
Author: User
Ref: http://csharpindepth.com/Articles/General/BluffersGuide2.aspx

Obviusly C # In depth teaches the new features of C #2In depth. However, if you want to bluff it for the moment (just until your copy of the book arrives, of course)-welcome to the bluffer's guide. this isn't intended to give you enough information to be useful when coding-but you can pretend you know what you're talking about in suitably geeky company. more seriously, it will give youVeryRough overview to give some context if you choose to investigate a particle feature further. (See also: bluffer's Guide to C #3 .)

Each of the major features of C #2 is here,:

    • A brief description of the feature, usually with an example
    • A couple of "extra bluff power" phrases to throw into conversation to get bonus points from your listeners-so long as they don't quiz you further
    • A couple of "call their bluff" claims which sound plausible, but are actually inaccurate. If you feel someone else is perhaps overstating their experience, see if they spot these traps.
Genericsdescription

Generics allow types and methods to be parameterised by other types. frankly it's a difficult idea to describe in few words, but it's best shown with an example:

// Without generics: arraylist
Arraylist listofstrings = new arraylist ();
Listofstrings. Add ("first ");
Listofstrings. Add ("second ");
Listofstrings. Add ("third ");
Listofstrings. Add (4); // Eek!
// Cast is necessary, as indexer just returns object
String y = (string) listofstrings [1];
// This will blow up when it reaches 4
Foreach (string X in listofstrings)
{
Console. writeline (X );
}
// With generics: List <t>
List <string> listofstrings = new list <string> ();
Listofstrings. Add ("first ");
Listofstrings. Add ("second ");
Listofstrings. Add ("third ");
// Compilation error! Compiler knows the list shoshould only contain strings
Listofstrings. Add (4 );
// No cast necessary: the list can only contain strings
String y = listofstrings [1];
// This is guaranteed to be okay
Foreach (string X in listofstrings)
{
Console. writeline (X );
}

Extra bluff power
    • When writing a generic type or method, you can addConstraintsTo type parameters. For instance,Nullable <t>Makes sure thatTIs a value type.
    • Generics in don't haveVarianceIn C #2 or 3-you can't convert fromIenumerable <string>ToIenumerable <Object>For example, even though every string is an object. This is a complex issue which is likely to bePartiallyAddressed in C #4. The capability already exists within the CLR.
Call their bluff (untrue statements)
    • Generics are just syntactic sugar-casts and checks saved med by the compiler. the runtime doesn' t know anything about them. (reality: that's broadly true in Java, but not in. net. the. net generics design keeps a lot more information than the Java version, giving it a lot more power in each areas .)
    • Generics can be applied to all types. (reality: You can declare generic classes, interfaces, delegates and structs-but not generic enums .)
Nullable types

Nullable types are value types which are wrappers roundOtherValue types (where the other type is specified with generics), allowing a "null value" to be represented. they are maid with database code, as databases often have nullable columns for numbers, dates and times, guids etc-all of which are value types in. net. theNullable <t>Structure is at the heart of nullable types, and C # has extra syntactic sugar with "? "Modifier and varous other neat features. For example:

// X, Y and Z are the same type
Int? X = NULL;
Nullable <int> Y = 10;
Int? Z = x + y;
If (Z = NULL)
{
Console. writeline ("null result ");
}
Else
{
// Note: Not nullable
Int result = Z. value;
Console. writeline ("Result: {0}", result );
}

Extra bluff power
    • The CLR knows about nullable types too-it makes sure that if you box the null value of a nullable type, you end up with a null reference. (and likewise you can Unbox a null reference to the null value of a nullable type .)
    • How operators work with nullable types is a language demo-. for instance, comparing twoInt?Values for duplicate ity always gives true or false in C #; in VB. NET it can result in null (if either side is null). Be careful when porting code!
Call their bluff (untrue statements)
    • Nullable <t>Constrains<T>To be a value type, but it's a value type itself. That means you can writeNullable <int>Even though it's not very useful. (Reality: A value type constraint explicitly excludes any nullable types .)
    • The null coalescing operator (??) Can only be used with a nullable type on the left hand side and its underlying non-nullable type on the right hand side. (reality: the null coalescing operator can be used with reference types, and the right hand side can also be a reference type or a nullable type. it can be useful to use the operator several times in a row, e.g.First ?? Second ?? Third. Indeed, the language is designed to enable this to work exactly how you 'd like it .)
Delegates (method group conversions and anonymous methods) Description

Delegates in C #2 have a number of improvements over C #1. The most important two features areImplicit Method group ConversionsAndAnonymous Methods, Both of which make it easier to create new instances of Delegate types. For example:

Public void Foo ()
{
// Do some stuff
}
// C #1 code:
Threadstart ts1 = new threadstart (FOO );
// C #2 code, implicit method group conversion:
Threadstart ts2 = Foo;
// C #2, anonymous method:
Threadstart ts3 = delegate {console. writeline ("Hi! ");};

There'sLotMore to anonymous methods than meets the eye, by the way...

Extra bluff power
    • Anonymous Methods actClosures, Allowing the delegate code to interact with the context in which it was created-including local variables.
    • Delegate construction in C #2 allows covariance/contravariance-so you can buildKeypresseventhandlerFromEventhandler, For instance-any parameters thatKeypresseventhandlerCan handle will be valid forEventhandlerToo.
Call their bluff (untrue statements)
    • Anonymous methods just add methods to the classes in which they're declared. (reality: Sometimes this is the case, but if local variables areCapturedThen extra types may be created .)
    • Anonymous methods can't update captured variables, just like Java's anonymous classes. (reality: the C # variable capture is much more subtle than Java's form. in Java, the variable'sValueIs captured; in C # The variable itself is captured .)
Iterator blocksdescription

Iterator blocks allowIenumerable <t>,Ienumerable,Ienumerator <t>AndIenumeratorTo be implemented very simply in C # code. for example, the code below will print out "start", "0", "1", "2", "3", "4", "end ".

Ienumerable <string> getsequence ()
{
Yield return "start ";
For (INT I = 0; I <5; I ++)
{
Yield return I. tostring ();
}
Yield return "end ";
}
...
Foreach (string X in getsequence ())
{
Console. writeline (I );
}

Extra bluff power
    • The compiler creates a new type for the iterator, which has member variables for the local variables in the iterator block.
    • Yield returnWhen tively "pauses" the method-next timeMovenextIs called (which happens implicitly inForeachStatements) Execution resumes from just afterYield return.
Call their bluff (untrue statements)
    • When the method is called (Getsequence ()In the above example), all the Code actually runs, and the results just get buffered intoList <t>.(Reality: such a scheme wowould completely defeat the point of iterators, and be impossible for infinite sequences. in fact, when the method is called almost nothing happens-an instance of the compiler-generated type is created and returned, but no user code executes. that starts happening whenMovenext ()Is called the first time .)
    • The CLR has special stack-handling code to keep the stack frame when the method was first called, so that the State can be kept. (reality: the CLR doesn't care that this is a compiler-generated iterator. the smarts are in the C # compiler, which converts the State required by the iterator block into member variables in the extra iterator type .)
Partial types

Partial types allow a single type to be built from multiple source files. this is Special useful with autogenerated Code, where the tool (e.g. a gui designer) can "own" one file, and the developer can work in a different one. thePartialKeyword is used to indicate that the type may span multiple files.

// Partial1.cs
Public partial class partial
{
Public void Foo ()
{
Bar (); // callinto a method declared in a different type
}
}
// Partial2.cs
Public partial class partial
{
Void bar ()
{
Console. writeline ("Hi! ");
}
}

Extra bluff power
    • Partial types apply to interfaces, classes and structs-but not enums or delegates.
    • Different files can indicate that a class implements different interfaces. The implementation of an interface doesn' t have to be in the same file.
Call their bluff (untrue statements)
    • Partial types spanning not just different source files, but differentAssembliesProvide a very powerful feature. (reality: Partial types are just a compile-time feature. A type itself still lives wholly within a single assembly .)
    • Partial types cannot be generic. (reality: they can be generic, and the type parameters can have constraints applied-but you can't specify some constraints in one file and different constraints in another .)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.