C# 6.0 功能簡介
今年將會上市的Visual Studio 2015 將會包含C# 6.0,那到底C# 6.0加了哪些新功能或語法呢?請看以下範例
- using Static
 
在C# 中都是使用using來將namespace的API引用。
C# 5.0
Console.WriteLine("Sample");
C# 6.0
using Console;
WriteLine("Sample");
可以直接將Static的Method用using "ClassName"就可以直接呼叫
- Auto property initializer(自動屬性初始化)
 
C# 5.0
public class SampleClass
{
	public string Name { get; set; }
	public SampleClass
	{
		Name = "Sample";
	}
}
C# 6.0
public class SampleClass
{
	public string Name { get; set; } = "Sample";
}
- Dictionary Initializer
 
C# 5.0
var dic = new Dictionary<string, string>()
{
	{"1", "A"},
	{"2", "B"}
};
C# 6.0
var dic = new Dictionary<string, string>()
{
	["1"] ="A",
	["2"] ="B"
};
var dic2 = new Dictionary<string, string>()
{
	[1] ="A",
	[2] ="B"
};
- nameof Expression
 
nameof 是在C# 6.0出現的新字眼,可以直接取的Property的Hardcoded name
C# 6.0
class SampleClass()
{
	public string ID { get; set; } = "A001";
	public string Name { get; set; } = "This is A Name";
}
void Main()
{
	var sample = new SampleClass();
	Console.WriteLine("{0} : {1}", nameof(SampleClass.ID), sample.ID);
	Console.WriteLine("{0} : {1}", nameof(SampleClass.Name), sample.Name);
}
- exception filter
 
在寫Code的時候很常會使用到Try Catch的方式避免一些非邏輯性錯誤但在catch的語法只能抓到那些類鞋的exception而不能使用其他參數加以判斷
C# 6.0
var str = new String();
try
{
	str = null;
}
catch (Exception ex) if( str !=null )
{
	Console.WriteLine("Error");
}
catch (Exception ex)
{
	Console.WriteLine(ex.Message);
}
- await can inside catch code block
 
在C# 5.0時有出現的Async和Await修飾字是使用在非同步執行續的Task上使用但如果使用try-catch的實在catch的程式碼區塊會無法使用await!但在C# 6.0時可以將await寫在catch的區塊了
C# 6.0
public async void GetData()
{
	try
	{
		var data = await httpClient.GetAsync("some uri here");
	}
	catch (Exception ex)
	{
		await httpClient.PostAsync("reuqest uri" , null);
	}
}
- Null conduction operator
 
在C# 中可以使用if-else的方式判斷也可以寫成
var data == "Some String" ? "true is here" : " false is here";
在C# 6.0的部分可以寫成
class Sample()
{
	public string P1 { get; set; } = "V1";
	public P2Class inside { get; set; }
}
class P2Class()
{
	public string P2V1 { get; set; } = "P2V1";
}
void Main()
{
	var sample = new Sample();
	Console.WriteLine(sample?.P1 + " " + sample?.inside?.P2V1??"Not set value yet");
}
先判斷sample是否為null 如果不是null救回傳sample的P1值,後面則是先判斷sample是否為null再判斷Inside是否為null若非null就會丟出P2V1的值要不然就是回傳Not set value yet
- Expression-bodied method
 
使用 lamda 取代掉大括號。
C# 5.0
public static string ShowTime()
{
	retrun DateTime.Now.ToString();
}
void main()
{
	Console.WriteLine(ShowTime());
}
C# 6.0
public static string ShowTime() => retrun DateTime.Now.ToString();
void main()
{
	Console.WriteLine(ShowTime());
}
- Easy string format
 
在C#可以使用String.format來結合字串以及變數!在6.0變得更加方便
C# 5.0
var v1 = "value 1";
var v2 = "value 2";
Console.WriteLine(String.Format("{0}, {1}", v1, v2));
C# 6.0
var v1 = "value 1";
var v2 = "value 2";
Console.WriteLine("\{v1}, \{v2}");
在C# 6.0帶來的以上幾種新的語法以及修飾字!若有錯誤請留言告知感謝~
參考資料