diff options
author | angelsl <angelsl@users.noreply.github.com> | 2016-10-02 20:09:49 +0800 |
---|---|---|
committer | ven <vendethiel@hotmail.fr> | 2016-10-02 14:09:49 +0200 |
commit | c9478229815195ba8b68623dea981986116b3d69 (patch) | |
tree | a5b1cd0b99716b65885d6346235b3a63f7f77866 /csharp.html.markdown | |
parent | b552fe30c2f3562cf670a9e7655ff834deb3b551 (diff) |
[csharp/en] Add more C# 6 features (#2399)
* C#: Add some new C# 6 features
* Remove trailing whitespace
Diffstat (limited to 'csharp.html.markdown')
-rw-r--r-- | csharp.html.markdown | 52 |
1 files changed, 48 insertions, 4 deletions
diff --git a/csharp.html.markdown b/csharp.html.markdown index 4c9e8411..a3d93a0b 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -459,7 +459,7 @@ on a new line! ""Wow!"", the masses cried"; if (i > limit/2) yield break; yield return i; } - } + } public static void OtherInterestingFeatures() { @@ -948,7 +948,7 @@ on a new line! ""Wow!"", the masses cried"; A.A2(); } } - + // String interpolation by prefixing the string with $ // and wrapping the expression you want to interpolate with { braces } public class Rectangle @@ -956,7 +956,7 @@ on a new line! ""Wow!"", the masses cried"; public int Length { get; set; } public int Width { get; set; } } - + class Program { static void Main(string[] args) @@ -965,7 +965,49 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}"); } } - + + // New C# 6 features + class GlassBall : IJumpable, IBreakable + { + // Autoproperty initializers + public int Damage { get; private set; } = 0; + + // Autoproperty initializers on getter-only properties + public string Name { get; } = "Glass ball"; + + // Getter-only autoproperty that is initialized in constructor + public string GenieName { get; } + + public GlassBall(string genieName = null) + { + GenieName = genieName; + } + + public void Jump(int meters) + { + if (meters < 0) + // New nameof() expression; compiler will check that the identifier exists + // nameof(x) == "x" + // Prevents e.g. parameter names changing but not updated in error messages + throw new ArgumentException("Cannot jump negative amount!", nameof(meters)); + + Damage += meters; + } + + // Expression-bodied properties ... + public bool Broken + => Damage > 100; + + // ... and methods + public override string ToString() + // Interpolated string + => $"{Name}. Damage taken: {Damage}"; + + public string SummonGenie() + // Null-conditional operators + // x?.y will return null immediately if x is null; y is not evaluated + => GenieName?.ToUpper(); + } } // End Namespace ``` @@ -973,6 +1015,8 @@ on a new line! ""Wow!"", the masses cried"; * Attributes * async/await, pragma directives + * Exception filters + * `using static` * Web Development * ASP.NET MVC & WebApi (new) * ASP.NET Web Forms (old) |