| Start |
|---|
| Exception filters Exception filters (opens new window) give developers the ability to add a condition (in the form of a Exception filters allow the propagation of debug information in the original exception, where as using an Exception filters have been supported by the CLR (opens new window) since the beginning and they've been accessible from VB.NET and F# for over a decade by exposing a part of the CLR's exception handling model. Only after the release of C# 6.0 has the functionality also been available for C# developers. Using exception filtersException filters are utilized by appending a Multiple Risky when clauseCaution
It can be risky to use exception filters: when an The following example illustrates such a scenario: Note that exception filters avoid the confusing line number problems associated with using The exception line number is reported as 6 because the error was caught and re-thrown with the The same does not happen with exception filters: In this example Logging as a side effectMethod calls in the condition can cause side effects, so exception filters can be used to run code on exceptions without catching them. A common example that takes advantage of this is a Be aware that while this seems to be a comfortable way of logging, it can be risky, especially if 3rd party logging assemblies are used. These might throw exceptions while logging in non-obvious situations that may not be detected easily (see Risky The common approach in previous versions of C# was to log and re-throw the exception. The |
| String interpolation String interpolation allows the developer to combine Basic ExampleTwo Output: The foo is 34, and the bar is 42. Braces within strings can still be used, like this: This produces the following output: The foo is {foo}, and the bar is {bar}. Using interpolation with verbatim string literalsUsing Output: In case it wasn't clear: ExpressionsWith string interpolation, expressions within curly braces Output: And the greater one is: 42 Note: Any leading or trailing whitespace (including space, tab and CRLF/newline) between the curly brace and the expression is completely ignored and not included in the output As another example, variables can be formatted as a currency: Output: Foo formatted as a currency to 4 decimal places: $34.0000 Or they can be formatted as dates: Output: Today is: Monday, July, 20 - 2015 Statements with a Conditional (Ternary) Operator (opens new window) can also be evaluated within the interpolation. However, these must be wrapped in parentheses, since the colon is otherwise used to indicate formatting as shown above: Output: Bar is larger than foo! Conditional expressions and format specifiers can be mixed: Output: Environment: 32-bit process Escape sequencesEscaping backslash ( Output: Foo is 34. In a non-verbatim string, we need to escape " and \ with backslashes. To include a curly brace Output: {foo} is: 34 FormattableString typeThe type of a This is also the order of type preference when the compiler needs to choose which overloaded method is going to be called. A new type (opens new window), Call the above method with:
For example, one could choose not to incur the performance cost of formatting the string if the logging level was already going to filter out the log item.Implicit conversionsThere are implicit type conversions from an interpolated string: You can also produce an Current and Invariant Culture MethodsIf code analysis is turned on, interpolated strings will all produce warning CA1305 (opens new window) (Specify Then, to produce a correct string for the current culture, just use the expression: Note:
string invariant = Invariant($"Now = {DateTime.Now}"); string current = $"Now = {DateTime.Now}"; The above will be converted to something like this: String Interpolation and LinqIt's possible to use interpolated strings in Linq statements to increase readability further. Can be re-written as: Reusable Interpolated StringsWith Interpolated strings, however, will not compile with placeholders referring to non-existent variables. The following will not compile: Instead, create a String interpolation and localizationIf you’re localizing your application you may wonder if it is possible to use string interpolation along with localization. Indeed, it would be nice to have the possibility to store in resource files
instead of the much less readable:
If the resource strings for the languages used above are correctly stored in the individual resource files, you should get the following output: Bonjour, mon nom est John Note that this implies that the name follows the localized string in every language. If that is not the case, you need to add placeholders to the resource strings and modify the function above or you need to query the culture info in the function and provide a switch case statement containing the different cases. For more details about resource files, see How to use localization in C# (opens new window). It is a good practice to use a default fallback language most people will understand, in case a translation is not available. I suggest to use English as default fallback language. Recursive interpolationAlthough not very useful, it is allowed to use an interpolated Output: String has 27 chars: My class is called MyClass. |
Auto-property initializers IntroductionProperties can be initialized with the Accessors With Different VisibilityYou can initialize auto-properties that have different visibility on their accessors. Here’s an example with a protected setter: The accessor can also be Read-Only PropertiesIn addition to flexibility with visibility, you can also initialize read-only auto-properties. Here’s an example: This example also shows how to initialize a property with a complex type. Also, auto-properties can’t be write-only, so that also precludes write-only initialization. Old style (pre C# 6.0)Before C# 6, this required much more verbose code. We were using one extra variable called backing property for the property to give default value or to initialize the public property like below, Note: Before C# 6.0, you could still initialize read and write auto implemented properties (opens new window) (properties with a getter and a setter) from within the constructor, but you could not initialize the property inline with its declaration UsageInitializers must evaluate to static expressions, just like field initializers. If you need to reference non-static members, you can either initialize properties in constructors like before, or use expression-bodied properties. Non-static expressions, like the one below (commented out), will generate a compiler error: But static methods can be used to initialize auto-properties: This method can also be applied to properties with different level of accessors: The auto-property initializer allows assignment of properties directly within their declaration. For read-only properties, it takes care of all the requirements required to ensure the property is immutable. Consider, for example, the Cautionary notesTake care to not confuse auto-property or field initializers with similar-looking expression-body methods (opens new window) which make use of For example, each of the following declarations are different. Missing The different symbol ( The above code is equivalent to: |
| Null propagation The This is useful, because if the Note that if the BasicsIf the If we modify this statement to use the Subsequently, if This is an example of short-circuiting: When any conditional access operation using the null-conditional operator evaluates to null, the entire expression evaluates to null immediately, without processing the rest of the chain. When the terminal member of an expression containing the null-conditional operator is of a value type, the expression evaluates to a Use with the Null-Coalescing Operator (??)You can combine the null-conditional operator with the Null-coalescing Operator (opens new window) ( Use with IndexersThe null-conditional operator can be used with indexers (opens new window): In the above example:
Use with void FunctionsNull-conditional operator can also be used with Use with Event InvocationAssuming the following event definition: When invoking an event, traditionally, it is best practice to check if the event is Since the null-conditional operator has been introduced, the invocation can be reduced to a single line: LimitationsNull-conditional operator produces rvalue, not lvalue, that is, it cannot be used for property assignment, event subscription etc. For example, the following code will not work: GotchasNote that: is not the same as: because the former corresponds to: and the latter corresponds to: Despite ternary operator Which outputs: Null propagation To avoid multiple invocations equivalent would be: And this difference somewhat explains why null propagation operator is not yet supported (opens new window) in expression trees. |
| Expression-bodied function members Expression-bodied function members allow the use of lambda expressions as member bodies. For simple members, it can result in cleaner and more readable code. Expression-bodied functions can be used for properties, indexers, methods, and operators. PropertiesIs equivalent to: When an expression-bodied function is used with a property, the property is implemented as a getter-only property. IndexersIs equivalent to: MethodsIs equivalent to: Which can also be used with An override of Additionally, this simplistic approach works with the OperatorsThis also can be used by operators: LimitationsExpression-bodied function members have some limitations. They can't contain block statements and any other statements that contain blocks: Some In all other cases, the old syntax for function members can be used. Expression-bodied function members can contain Can be replaced with: |
| Operator nameof The The Since It is convenient to use it is possible to use: The output will be The Can be replaced with: The output will be Although the Furthermore, if you apply it to a generic type, the generic type parameter will be ignored: For more examples, see this topic (opens new window) dedicated to Workaround for previous versions (more detail (opens new window))Although the Expression: Usage: Note that this approach causes an expression tree to be created on every call, so the performance is much worse compared to |
| Using static type The Live Demo Fiddle (opens new window) |
| Index initializers Index initializers make it possible to create and initialize objects with indexes at the same time. This makes initializing Dictionaries very easy: Any object that has an indexed getter or setter can be used with this syntax: Output: Index: foo, value: 34 If the class has multiple indexers it is possible to assign them all in a single group of statements: Output: Index: foo, value: 34 It should be noted that the indexer For example: versus: |
| Improved overload resolution Following snippet shows an example of passing a method group (as opposed to a lambda) when a delegate is expected. Overload resolution will now resolve this instead of raising an ambiguous overload error due to the ability of C# 6 to check the return type of the method that was passed. Results: Output overload with Func Error error CS0121: The call is ambiguous between the following methods or properties: 'Program.Overloaded(System.Action)' and 'Program.Overloaded(System.Func)' C# 6 can also handle well the following case of exact matching for lambda expressions which would have resulted in an error in C# 5. |
| Await in catch and finally It is possible to use It was not possible to use the It was required in C# 5 to use a |
| Minor changes and bugfixes Parentheses are now forbidden around named parameters. The following compiles in C#5, but not C#6 Operands of The native compiler allowed this (although it did show a warning), and in fact didn’t even check extension method compatibility, allowing crazy things like See this reference (opens new window) for updates on changes. |
| Using an extension method for collection initialization Collection initialization syntax can be used when instantiating any class which implements In previous versions, this This will output: Item added with instance add method: 1 |
| Disable Warnings Enhancements In C# 5.0 and earlier the developer could only suppress warnings by number. With the introduction of Roslyn Analyzers, C# needs a way to disable warnings issued from specific libraries. With C# 6.0 the pragma directive can suppress warnings by name. Before: C# 6.0: RemarksThe sixth version of C# was released July 2015 alongside Visual Studio 2015 and .NET 4.6. As well as adding some new language features it includes a complete rewrite of the compiler. Previously |
Read Article
https://develop.horje.com/learn/1434/reference