Home > Backend Development > C#.Net Tutorial > 10 Features in C# You Really Should Learn (and Use!)

10 Features in C# You Really Should Learn (and Use!)

高洛峰
Release: 2017-02-08 13:24:15
Original
1194 people have browsed it

If you start exploring C# or decide to expand your knowledge, then you should learn these useful language features. Doing so will help simplify your code, avoid errors, and save a lot of time.

 

1) async/await

Using async/await-pattern allows unblocking the UI/current thread when performing blocking operations. The async/await-pattern works by allowing code to continue executing even if something blocks execution (like a web request).


2) Object/array/collection initializer

By using object, array and collection initializers, you can easily create classes, arrays and collections Example:


//Some demonstration classes publicclassEmployee{ publicstringName { get; set;} publicDateTime StartDate { get; set;}} //Use initializer to create employee Employee emp = newEmployee {Name= "John Smith", StartDate=DateTime.Now()};


The above example is only really useful in unit testing, but should be used in other contexts Avoid because instances of classes should be created using constructors.


3) Lambdas, predicates, delegates and closures

In many cases (such as when using Linq), these features are actually required, Make sure to learn when and how to use them.


4) ?? (null coalescing operator)

?? – operator returns the left side as long as it is not null; in that case Return the right side:


//May be null varsomeValue = service. GetValue(); vardefaultValue = 23//If someValue is null, the result will be 23 varresult = someValue ?? defaultValue ;


?? – Operators can be chained:

stringanybody = parm1 ?? localDefault ?? globalDefault;


And it can be used to convert nullable types to non-nullable:

vartotalPurchased = PurchaseQuantities.Sum(kvp => kvp.Value ?? 0);


5) $"{x}" (string interpolation) ——C#6


This is for C#6 A new feature that allows you to assemble strings in an efficient and elegant way:


//Old method varsomeString = String.Format( "Some data: {0}, some more data: {1}", someVariable, someOtherVariable); //New method varsomeString = $"Some data: {someVariable}, some more data: {someOtherVariable}";


You can put C# expressions between curly braces, which makes this string interpolation very powerful.


6)?.(Null conditional operator) ——C#6

The null conditional operator works as follows:


//Null ifcustomer orcustomer.profile orcustomer.profile.age isnullvar currentAge = customer?.profile?.age;


No updates Lots of NullReferenceExceptions!


7) nameof Expression - C#6

The new nameof-expression may not seem important, but it really has its value . When using automatic refactoring tools (such as ReSharper), you sometimes need to reference method parameters by name:


publicvoid PrintUserName(UsercurrentUser){ //The refactoring tool might miss the textual reference to current user below ifwe're renaming it if(currentUser == null) _logger. Error( "Argument currentUser is not provided"); //...}


You should use it like this...


publicvoidPrintUserName(User currentUser){ //The refactoring tool will not miss this...if(currentUser == null) _logger .Error( $"Argument {nameof(currentUser)}is not provided"); //...} 8) Property initializer - C#6


property Initializers allow you to declare the initial value of a property:

publicclassUser{ publicGuidId{ get; } = Guid. NewGuid(); // ...}


One benefit of using property initializers is that you cannot declare a collection: well, thus making the property immutable. Property initializers work with C#6 primary constructor syntax.


9) as and is operators


is operator is used to control whether an instance is of a specific type, for example , if you want to see if it's possible to convert:


if( PersonisAdult){ //do stuff}


Use the as operator to try to convert an instance to a class. If it cannot be converted, it will return null:


SomeType y = x asSomeType; if(y != null){ //do stuff} 10) yield keyword


The yield keyword allows providing an IEnumerable interface with entries. The following example will return every power of 2 from 2 to 8 (for example, 2,4,8,16,32,64,128,256):


publicstaticIEnumerable Power( intnumber, intexponent){ intresult = 1; for( inti = 0; i < exponent; i++) { result = result * number; yieldreturnresult; }}


yield returns Can be very powerful, if it's used in the right way. It enables you to lazily generate a collection of objects, i.e. the system doesn't have to enumerate the entire collection - it just does it on demand.

For more articles related to 10 functions in C# that you really should learn (and use!), please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template