From e675c887fe27538805a2b8deddf3f3d37a653d7c Mon Sep 17 00:00:00 2001 From: Dean Becker Date: Tue, 20 Oct 2015 16:32:49 +0100 Subject: Expanded XML Doc example Just an expansion of the XML documentation example, the tag can be very useful in Visual Studio, especially. --- csharp.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index dfdd98de..c844c479 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -24,7 +24,9 @@ Multi-line comments look like this /// This is an XML documentation comment which can be used to generate external /// documentation or provide context help within an IDE /// -//public void MethodOrClassOrOtherWithParsableHelp() {} +/// This is some parameter documentation for firstParam +/// Information on the returned value of a function +//public void MethodOrClassOrOtherWithParsableHelp(string firstParam) {} // Specify the namespaces this source code will be using // The namespaces below are all part of the standard .NET Framework Class Libary -- cgit v1.2.3 From 33ffabafc5e9d80670561d6e3096dfc449b3d487 Mon Sep 17 00:00:00 2001 From: "chris@chriszimmerman.net" Date: Thu, 22 Oct 2015 21:21:33 -0400 Subject: Fixed minor grammatical change. --- csharp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index dfdd98de..83efdfb6 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -879,8 +879,8 @@ on a new line! ""Wow!"", the masses cried"; bool Broken { get; } // interfaces can contain properties as well as methods & events } - // Class can inherit only one other class, but can implement any amount of interfaces, however - // the base class name must be the first in the list and all interfaces follow + // Classes can inherit only one other class, but can implement any amount of interfaces, + // however the base class name must be the first in the list and all interfaces follow class MountainBike : Bicycle, IJumpable, IBreakable { int damage = 0; -- cgit v1.2.3 From 04a01fe872d7f2fb71de893fce122b54c68b4ae6 Mon Sep 17 00:00:00 2001 From: "chris@chriszimmerman.net" Date: Thu, 22 Oct 2015 21:38:55 -0400 Subject: Cleaned up enum flags example. Talked about bitwise operators & and |. --- csharp.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 83efdfb6..6f11d8a1 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -692,7 +692,10 @@ on a new line! ""Wow!"", the masses cried"; public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type // Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on - [Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc + // Any class derived from Attribute can be used to decorate types, methods, parameters etc + // Bitwise operators & and | can be used to perform and/or operations + + [Flags] public enum BikeAccessories { None = 0, -- cgit v1.2.3 From 8b06524f3d74baeedb1be2cee2b95b20ffab7406 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Sun, 13 Mar 2016 01:03:23 -0700 Subject: [csharp/en] libary -> library --- csharp.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 7d7f4340..bcb35d4b 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -27,7 +27,7 @@ Multi-line comments look like this //public void MethodOrClassOrOtherWithParsableHelp() {} // Specify the namespaces this source code will be using -// The namespaces below are all part of the standard .NET Framework Class Libary +// The namespaces below are all part of the standard .NET Framework Class Library using System; using System.Collections.Generic; using System.Dynamic; @@ -421,7 +421,7 @@ on a new line! ""Wow!"", the masses cried"; // Item is an int Console.WriteLine(item.ToString()); } - + // YIELD // Usage of the "yield" keyword indicates that the method it appears in is an Iterator // (this means you can use it in a foreach loop) @@ -437,7 +437,7 @@ on a new line! ""Wow!"", the masses cried"; foreach (var counter in YieldCounter()) Console.WriteLine(counter); } - + // you can use more than one "yield return" in a method public static IEnumerable ManyYieldCounter() { @@ -446,7 +446,7 @@ on a new line! ""Wow!"", the masses cried"; yield return 2; yield return 3; } - + // you can also use "yield break" to stop the Iterator // this method would only return half of the values from 0 to limit. public static IEnumerable YieldCounterWithBreak(int limit = 10) @@ -482,7 +482,7 @@ on a new line! ""Wow!"", the masses cried"; // ?? is syntactic sugar for specifying default value (coalesce) // in case variable is null int notNullable = nullable ?? 0; // 0 - + // ?. is an operator for null-propagation - a shorthand way of checking for null nullable?.Print(); // Use the Print() extension method if nullable isn't null @@ -913,17 +913,17 @@ on a new line! ""Wow!"", the masses cried"; public DbSet Bikes { get; set; } } - + // Classes can be split across multiple .cs files // A1.cs - public partial class A + public partial class A { public static void A1() { Console.WriteLine("Method A1 in class A"); } } - + // A2.cs public partial class A { @@ -932,9 +932,9 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine("Method A2 in class A"); } } - + // Program using the partial class "A" - public class Program + public class Program { static void Main() { -- cgit v1.2.3 From ef486c21197c30d39399f695bb5414b50ef6c4ac Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 2 May 2016 15:15:23 -0700 Subject: Clarify inc/dec operators --- csharp.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 7be34fb9..8d185462 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -212,10 +212,10 @@ on a new line! ""Wow!"", the masses cried"; // Incrementations int i = 0; Console.WriteLine("\n->Inc/Dec-rementation"); - Console.WriteLine(i++); //i = 1. Post-Incrementation - Console.WriteLine(++i); //i = 2. Pre-Incrementation - Console.WriteLine(i--); //i = 1. Post-Decrementation - Console.WriteLine(--i); //i = 0. Pre-Decrementation + Console.WriteLine(i++); //Prints "0", i = 1. Post-Incrementation + Console.WriteLine(++i); //Prints "2", i = 2. Pre-Incrementation + Console.WriteLine(i--); //Prints "2", i = 1. Post-Decrementation + Console.WriteLine(--i); //Prints "0", i = 0. Pre-Decrementation /////////////////////////////////////// // Control Structures -- cgit v1.2.3 From e9ce4e2e6e401b9bb1f495d35c57141b4cffba22 Mon Sep 17 00:00:00 2001 From: Shawn McGuire Date: Sun, 26 Jun 2016 07:47:36 -0500 Subject: [csharp/en] Add string interpolation (#1864) Added example of using string interpolation --- csharp.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 8d185462..69aef257 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Wouter Van Schandevijl", "http://github.com/laoujin"] - ["Jo Pearce", "http://github.com/jdpearce"] - ["Chris Zimmerman", "https://github.com/chriszimmerman"] + - ["Shawn McGuire", "https://github.com/bigbash"] filename: LearnCSharp.cs --- @@ -947,6 +948,24 @@ 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 + { + public int Length { get; set; } + public int Width { get; set; } + } + + class Program + { + static void Main(string[] args) + { + Rectangle rect = new Rectangle { Length = 5, Width = 3 }; + Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}"); + } + } + } // End Namespace ``` -- cgit v1.2.3 From c0577fece6b2862a7198b61ec1855b504cf43d47 Mon Sep 17 00:00:00 2001 From: Durant Schoon Date: Mon, 27 Jun 2016 23:53:25 -0700 Subject: Correct "Bycles" to "Bicycles"" (#2293) "DidWeCreateEnoughBycles" -> "DidWeCreateEnoughBicycles" --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 69aef257..4c9e8411 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -826,7 +826,7 @@ on a new line! ""Wow!"", the masses cried"; } // Methods can also be static. It can be useful for helper methods - public static bool DidWeCreateEnoughBycles() + public static bool DidWeCreateEnoughBicycles() { // Within a static method, we only can reference static class members return BicyclesCreated > 9000; -- cgit v1.2.3 From c9478229815195ba8b68623dea981986116b3d69 Mon Sep 17 00:00:00 2001 From: angelsl Date: Sun, 2 Oct 2016 20:09:49 +0800 Subject: [csharp/en] Add more C# 6 features (#2399) * C#: Add some new C# 6 features * Remove trailing whitespace --- csharp.html.markdown | 52 ++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 4 deletions(-) (limited to 'csharp.html.markdown') 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) -- cgit v1.2.3 From 7b96973204f7309b5a42be10e4e24a0bb005ba85 Mon Sep 17 00:00:00 2001 From: chriszimmerman Date: Tue, 11 Oct 2016 03:33:17 -0400 Subject: Csharp parallel (#2443) * [csharp/en] - Attempts to address issue #1064 by using a different parallel example. --- csharp.html.markdown | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index a3d93a0b..2cacfc00 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -547,28 +547,22 @@ on a new line! ""Wow!"", the masses cried"; // PARALLEL FRAMEWORK // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx - var websites = new string[] { - "http://www.google.com", "http://www.reddit.com", - "http://www.shaunmccarthy.com" - }; - var responses = new Dictionary(); - // Will spin up separate threads for each request, and join on them - // before going to the next step! - Parallel.ForEach(websites, - new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads - website => - { - // Do something that takes a long time on the file - using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + var words = new List {"dog", "cat", "horse", "pony"}; + + Parallel.ForEach(words, + new ParallelOptions() { MaxDegreeOfParallelism = 4 }, + word => { - responses[website] = r.ContentType; + Console.WriteLine(word); } - }); + ); - // This won't happen till after all requests have been completed - foreach (var key in responses.Keys) - Console.WriteLine("{0}:{1}", key, responses[key]); + //Running this will produce different outputs + //since each thread finishes at different times. + //Some example outputs are: + //cat dog horse pony + //dog horse pony cat // DYNAMIC OBJECTS (great for working with other languages) dynamic student = new ExpandoObject(); -- cgit v1.2.3 From d48aef96f1b1db80a6d752cf3a076673535c3071 Mon Sep 17 00:00:00 2001 From: Chris Date: Fri, 21 Oct 2016 11:46:25 -0400 Subject: Added example of C# inline properties (#1464) This was a really cool & useful trick/feature that I found while learning C#. --- csharp.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 2cacfc00..442700a6 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -671,6 +671,10 @@ on a new line! ""Wow!"", the masses cried"; int _speed; // Everything is private by default: Only accessible from within this class. // can also use keyword private public string Name { get; set; } + + // Properties also have a special syntax for when you want a readonly property + // that simply returns the result of an expression + public string LongName => Name + " " + _speed + " speed"; // Enum is a value type that consists of a set of named constants // It is really just mapping a name to a value (an int, unless specified otherwise). -- cgit v1.2.3 From eb1ed1729b9d9539e16e17590cfb911cd72a279e Mon Sep 17 00:00:00 2001 From: angelsl Date: Fri, 10 Feb 2017 00:40:04 +0800 Subject: [csharp/en] Add exception filters, pragma directives (#2409) * [csharp/en] Add exception filters, pragma directives * Remove redundant catch --- csharp.html.markdown | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 89 insertions(+), 3 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 442700a6..cca99fb0 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -1006,15 +1006,101 @@ on a new line! ""Wow!"", the masses cried"; // x?.y will return null immediately if x is null; y is not evaluated => GenieName?.ToUpper(); } + + static class MagicService + { + private static bool LogException(Exception ex) + { + /* log exception somewhere */ + return false; + } + + public static bool CastSpell(string spell) + { + try + { + // Pretend we call API here + throw new MagicServiceException("Spell failed", 42); + + // Spell succeeded + return true; + } + // Only catch if Code is 42 i.e. spell failed + catch(MagicServiceException ex) when (ex.Code == 42) + { + // Spell failed + return false; + } + // Other exceptions, or MagicServiceException where Code is not 42 + catch(Exception ex) when (LogException(ex)) + { + // Execution never reaches this block + // The stack is not unwound + } + return false; + // Note that catching a MagicServiceException and rethrowing if Code + // is not 42 or 117 is different, as then the final catch-all block + // will not catch the rethrown exception + } + } + + public class MagicServiceException : Exception + { + public int Code { get; } + + public MagicServiceException(string message, int code) : base(message) + { + Code = code; + } + } + + public static class PragmaWarning { + // Obsolete attribute + [Obsolete("Use NewMethod instead", false)] + public static void ObsoleteMethod() + { + /* obsolete code */ + } + + public static void NewMethod() + { + /* new code */ + } + + public static void Main() + { + ObsoleteMethod(); // CS0618: 'ObsoleteMethod is obsolete: Use NewMethod instead' +#pragma warning disable CS0618 + ObsoleteMethod(); // no warning +#pragma warning restore CS0618 + ObsoleteMethod(); // CS0618: 'ObsoleteMethod is obsolete: Use NewMethod instead' + } + } } // End Namespace + +using System; +// C# 6, static using +using static System.Math; + +namespace Learning.More.CSharp +{ + class StaticUsing + { + static void Main() + { + // Without a static using statement.. + Console.WriteLine("The square root of 4 is {}.", Math.Sqrt(4)); + // With one + Console.WriteLine("The square root of 4 is {}.", Sqrt(4)); + } + } +} ``` ## Topics Not Covered * Attributes - * async/await, pragma directives - * Exception filters - * `using static` + * async/await * Web Development * ASP.NET MVC & WebApi (new) * ASP.NET Web Forms (old) -- cgit v1.2.3