Some New Features in C# 6.0

Static Using Syntax

In previous versions of C#, we would need to add the proper using statement, such as System, then we could write the following line of code:

  1. Console.WriteLine("Hello Abrar!");

With C# 6, you can now add the using statement and reference the WriteLine method by itself as in the following:

  1. using System.Console;
  2. namespace Console1
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args
  7. {
  8. //Sample One
  9. WriteLine("Hello Abrar!");
  10. }
  11. }
  12. }

Auto-Property Initializers

In the past, we may have created our properties with a get and set and then initialized our constructor with the value that we wanted as shown below.

  1. public class Customer
  2. {
  3. public Customer()
  4. {
  5. customerID = Guid.NewGuid();
  6. }
  7. public Guid customerID
  8. {
  9. get;
  10. set;
  11. }
  12. }

We can now reduce this code block to one line as shown below. No longer do we need to create a setter or constructor.

  1. public class Customer
  2. {
  3. public Guid customerID { get; set; } = Guid.NewGuid();
  4. }

Dictionary Initializers

Many C# developers felt the format shown below was confusing for creating dictionaries, mainly because of the use of brackets and quotation marks for the data.

  1. Dictionary<string, string> customerNames = new Dictionary<string, string>()
  2. {
  3. { "Abrar Ahmad", ".net" },
  4. { "Yogesh", "Java" },
  5. { "Ganesh", "SQL" }
  6. };

The compiler team decided to change this and make it more readable with the following format. This new format will only save you a few keystrokes, but it is much easier to read in my opinion.

  1. public Dictionary<string, string> customerNames = new Dictionary<string, string>()
  2. {
  3. ["Abrar Ahmad "] = ". net ",
  4. ["Yogesh"] = "Java",
  5. ["Ganesh "] = " SQL "
  6. };

Exception Filters and Async in a Catch and Finally Block

Exception Filters

Exception filters have been supported in Visual Basic, but are new to the C# compiler. They allow you to specify a condition for a catch block. As shown in the following sample, the last catch statement will fire.

  1. public static async void DownloadAsync()
  2. {
  3. try
  4. {
  5. throw new Exception("Error");
  6. } catch
  7. {
  8. await Task.Delay(2000);
  9. WriteLine("Waiting 2 seconds");
  10. }
  11. finally
  12. {
  13. await Task.Delay(2000);
  14. WriteLine("Waiting 2 seconds");
  15. }
  16. }

Async in a Catch and Finally Block

I think many developers will love this feature because they often need to log exceptions to a file or database without blocking the current thread. Here is an example of how one would work:

  1. public static async void DownloadAsync()
  2. {
  3. try
  4. {
  5. throw new Exception("Error");
  6. }
  7. catch
  8. {
  9. await Task.Delay(2000);
  10. WriteLine("Waiting 2 seconds");
  11. }
  12. finally
  13. {
  14. await Task.Delay(2000);
  15. WriteLine("Waiting 2 seconds");
  16. }
  17. }

Name of Expressions

How many times in your code do you retrieve the name of a member of your class? You would typically wrap the field in quotation marks as shown below.

  1. public static void DoSomething(string name)
  2. {
  3. if (name != null) throw new Exception("name");
  4. }

The main problem with this is that it forces you to put strings in your code to represent the name of a member. In C# 6.0, there is a new operator called nameof that will allow us to refactor our code to remove these string literals. The sample shown below will show how we could refactor that same method.

  1. public static void DoSomething(string name)
  2. {
  3. if (name != null) throw new Exception(nameof(name));
  4. }

This results in cleaner code and safety when retrieving member names.

String Interpolation

Prior to C# 6.0, we typically concatenate two or more strings together in one of the following ways:

  1. string firstName = "Abrar";
  2. string lastName = "Ahmad";
  3. WriteLine("Name : " + firstName + " " + lastName);
  4. WriteLine(string.Format("Name : {0} {1}", firstName, lastName));

In C# 6.0, we have a cleaner format as shown in the first WriteLine call, but we can also put expressions directly in the string literal to evaluate an expression as shown below:

  1. string firstName = "Abrar";
  2. string lastName = "Ahmad";
  3. WriteLine("Name : \{firstName} \{lastName}");

src: By Abrar Ahmad Ansari on Apr 10, 2015

http://www.c-sharpcorner.com/UploadFile/d06872/some-new-features-in-C-Sharp-6-0/

时间: 2024-12-18 11:31:46

Some New Features in C# 6.0的相关文章

New features introduced in 8.0 类似Oracle SPFILE

mysql> set persist innodb_buffer_pool_size=2048*1024*1024; Query OK, 0 rows affected (0.01 sec) mysql> show variables like 'innodb_buffer_pool_size'; +-------------------------+------------+ | Variable_name | Value | +-------------------------+-----

Android开发如何在4.0及以上系统中自定义TitleBar

本文将通过一个实例讲解怎么实现在4.0及以上系统版本中实现自定义TitleBar,这只是我自己找到的一种方法; xml布局文件 activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="m

Microsoft .NET Pet Shop 4: Migrating an ASP.NET 1.1 Application to 2.0

249 out of 297 rated this helpful - Rate this topic Gregory LeakeMicrosoft Corporation Alan Le, Alex Arkhipov, Mike Hanley, and Steve NyholmVertigo Software, Inc. February 2006 Applies to:    Microsoft .NET Framework 2.0     Microsoft Visual Studio 2

(转)SDL 1.2 to 2.0 Migration Guide--SDL1.2更新到SDL2.0指南

SDL 1.2 to 2.0 Migration Guide 目录 SDL 1.2 to 2.0 Migration Guide Translations Introduction Overview of new features Looking for more information Moving from SDL 1.2 to 2.0 Some general truths Video Setting up a game with the new video API If your gam

HPDL380G8平台11.2.0.3 RAC实施手册

HPDL380G8平台11.2.0.3 RAC实施手册   1 前言 此文档详细描述了Oracle 11gR2 数据库在HPDL380G上的安装RAC的检查及安装步骤.文档中#表示root用户执行,$表示grid或oracle用户执行. 2 系统环境 1.操作系统环境 说明项 节点1 节点2 硬件型号 HPDL380pGen8 HPDL380pGen8 操作系统 Oel6.4 Oel6.4 集群件 oracle grid oracle grid 服务器主机名 Rbdb81 Rbdb82 IP地址

实战~REDHAT 6.5 X64上安装ORACLE双机(ROSE-HA9.0)

以下是一次实施的全程介绍,非虚拟机环境. 1.系统环境配置介绍 1.1.操作系统规划 主机名 服务器配置 操作系统版本 安装数据库版本 双机软件版本 Jzzf-db1 E5-2609 v3*2 128GB内存 300G硬盘 Redhat linux 6.5 x64 Oracle 10.2.0.5 Rose ha 9.0 Jzzf-db2 E5-2609 v3*2 128GB内存 300G硬盘 Redhat linux 6.5 x64 Oracle 10.2.0.5 Rose ha 9.0 1.2

Networkx study notes(0)

Networkx Class Type Self-loops allowed Parallel edges allowed Graph undirected Yes No DiGraph directed Yes No MultiGraph undirected Yes Yes MultiDiGraph directed Yes Yes There are two methods to grow the Graph : import networkx as nx import matplotli

Vector Tile

Mapbox Vector Tile Specification A specification for encoding tiled vector data. <?XML:NAMESPACE PREFIX = "[default] http://www.w3.org/2000/svg" NS = "http://www.w3.org/2000/svg" />License The text of this specification is licens

Python - Seaborn可视化:图形个性化设置的几个小技巧

1 概述 在可视化过程中,经常会对默认的制图效果不满意,希望能个性化进行各种设置. 本文通过一个简单的示例,来介绍seaborn可视化过程中的个性化设置.包括常用的设置,如: 设置图表显示颜色 设置图表标题,包括显示位置,字体大小,颜色等 设置x轴和y轴标题,包括颜色,字体大小 设置x轴和y轴刻度内容,包括颜色.字体大小.字体方向等 将x轴和y轴内容逆序显示 设置x轴或y轴显示位置 本文的运行环境: windows 7 python 3.5 jupyter notebook seaborn 0.