├── .gitignore
├── LICENSE
├── README.md
├── csharp-seven-kata-tests
├── AsyncReturnKataTests.cs
├── ExpressionBodyKataTests.cs
├── LocalFunctionsKataTests.cs
├── LocalReferencesKataTests.cs
├── NumericLiteralSyntaxTests.cs
├── OutVariablesKataTests.cs
├── PatternMatchingKataTests.cs
├── ThrowExpressionsKataTests.cs
├── TupleKataTests.cs
└── csharp-seven-kata-tests.csproj
└── csharp-seven-kata
├── AsyncReturnKata.cs
├── ExpressionBodyKata.cs
├── LocalFunctionsKata.cs
├── LocalReferencesKata.cs
├── NumericLiteralSyntaxKata.cs
├── OutVariablesKata.cs
├── PatternMatchingKata.cs
├── ThrowExpressionsKata.cs
├── TupleKata.cs
├── csharp-seven-kata.csproj
└── csharp-seven-kata.sln
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 | *.VC.VC.opendb
85 |
86 | # Visual Studio profiler
87 | *.psess
88 | *.vsp
89 | *.vspx
90 | *.sap
91 |
92 | # TFS 2012 Local Workspace
93 | $tf/
94 |
95 | # Guidance Automation Toolkit
96 | *.gpState
97 |
98 | # ReSharper is a .NET coding add-in
99 | _ReSharper*/
100 | *.[Rr]e[Ss]harper
101 | *.DotSettings.user
102 |
103 | # JustCode is a .NET coding add-in
104 | .JustCode
105 |
106 | # TeamCity is a build add-in
107 | _TeamCity*
108 |
109 | # DotCover is a Code Coverage Tool
110 | *.dotCover
111 |
112 | # NCrunch
113 | _NCrunch_*
114 | .*crunch*.local.xml
115 | nCrunchTemp_*
116 |
117 | # MightyMoose
118 | *.mm.*
119 | AutoTest.Net/
120 |
121 | # Web workbench (sass)
122 | .sass-cache/
123 |
124 | # Installshield output folder
125 | [Ee]xpress/
126 |
127 | # DocProject is a documentation generator add-in
128 | DocProject/buildhelp/
129 | DocProject/Help/*.HxT
130 | DocProject/Help/*.HxC
131 | DocProject/Help/*.hhc
132 | DocProject/Help/*.hhk
133 | DocProject/Help/*.hhp
134 | DocProject/Help/Html2
135 | DocProject/Help/html
136 |
137 | # Click-Once directory
138 | publish/
139 |
140 | # Publish Web Output
141 | *.[Pp]ublish.xml
142 | *.azurePubxml
143 | # TODO: Comment the next line if you want to checkin your web deploy settings
144 | # but database connection strings (with potential passwords) will be unencrypted
145 | *.pubxml
146 | *.publishproj
147 |
148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
149 | # checkin your Azure Web App publish settings, but sensitive information contained
150 | # in these scripts will be unencrypted
151 | PublishScripts/
152 |
153 | # NuGet Packages
154 | *.nupkg
155 | # The packages folder can be ignored because of Package Restore
156 | **/packages/*
157 | # except build/, which is used as an MSBuild target.
158 | !**/packages/build/
159 | # Uncomment if necessary however generally it will be regenerated when needed
160 | #!**/packages/repositories.config
161 | # NuGet v3's project.json files produces more ignoreable files
162 | *.nuget.props
163 | *.nuget.targets
164 |
165 | # Microsoft Azure Build Output
166 | csx/
167 | *.build.csdef
168 |
169 | # Microsoft Azure Emulator
170 | ecf/
171 | rcf/
172 |
173 | # Windows Store app package directories and files
174 | AppPackages/
175 | BundleArtifacts/
176 | Package.StoreAssociation.xml
177 | _pkginfo.txt
178 |
179 | # Visual Studio cache files
180 | # files ending in .cache can be ignored
181 | *.[Cc]ache
182 | # but keep track of directories ending in .cache
183 | !*.[Cc]ache/
184 |
185 | # Others
186 | ClientBin/
187 | ~$*
188 | *~
189 | *.dbmdl
190 | *.dbproj.schemaview
191 | *.pfx
192 | *.publishsettings
193 | node_modules/
194 | orleans.codegen.cs
195 |
196 | # Since there are multiple workflows, uncomment next line to ignore bower_components
197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
198 | #bower_components/
199 |
200 | # RIA/Silverlight projects
201 | Generated_Code/
202 |
203 | # Backup & report files from converting an old project file
204 | # to a newer Visual Studio version. Backup files are not needed,
205 | # because we have git ;-)
206 | _UpgradeReport_Files/
207 | Backup*/
208 | UpgradeLog*.XML
209 | UpgradeLog*.htm
210 |
211 | # SQL Server files
212 | *.mdf
213 | *.ldf
214 |
215 | # Business Intelligence projects
216 | *.rdl.data
217 | *.bim.layout
218 | *.bim_*.settings
219 |
220 | # Microsoft Fakes
221 | FakesAssemblies/
222 |
223 | # GhostDoc plugin setting file
224 | *.GhostDoc.xml
225 |
226 | # Node.js Tools for Visual Studio
227 | .ntvs_analysis.dat
228 |
229 | # Visual Studio 6 build log
230 | *.plg
231 |
232 | # Visual Studio 6 workspace options file
233 | *.opt
234 |
235 | # Visual Studio LightSwitch build output
236 | **/*.HTMLClient/GeneratedArtifacts
237 | **/*.DesktopClient/GeneratedArtifacts
238 | **/*.DesktopClient/ModelManifest.xml
239 | **/*.Server/GeneratedArtifacts
240 | **/*.Server/ModelManifest.xml
241 | _Pvt_Extensions
242 |
243 | # Paket dependency manager
244 | .paket/paket.exe
245 | paket-files/
246 |
247 | # FAKE - F# Make
248 | .fake/
249 |
250 | # JetBrains Rider
251 | .idea/
252 | *.sln.iml
253 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Nick Floyd
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # C# 7 Kata
2 |
3 | A kata that helps you practice and discover the [new language features of C# 7](https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7)
4 |
5 | **Kata** originally were teaching and training methods by which successful combat techniques were preserved and passed on. Practicing kata allowed a company of persons to engage in a struggle using a systematic approach, rather than as individuals in a disorderly manner. [source](https://en.wikipedia.org/wiki/Kata)
6 |
7 | ### Definition
8 |
9 | In this Kata we will learn how to use new features from C# 7 such as `out variables`, `ValueTuples`, `Pattern Matching`, `ref locals and returns`, `Local Functions`, `expression-bodied members`, `throw Expressions`, `Generalized async return types`, and `Numeric literal syntax improvements`. Make sure to visit the links below for some really great content that will help you navigate these katas.
10 |
11 | **Note:** All kata directions will be found in each of the corresponding .cs files.
12 |
13 | ### Requirements
14 |
15 | * Visual Studio 2017 (any edition) OR .NET Core CLI + any code editor (Visual Studio Code, etc.)
16 | * Understanding of .NET Framework
17 | * Understanding of C#
18 |
19 | ### How to approach
20 | * The csharp-seven-kata project contains classes covering each language feature area.
21 | * Using your preferred editor, follow the kata instructions in each class to learn how to use each new language feature.
22 | * Run the tests to verify success!
23 | * Visual Studio 2017
24 | * Test Explorer > Run All
25 | * .NET Core CLI
26 | * Navigate to `\csharp-seven-kata\csharp-seven-kata-tests\`
27 | * `dotnet restore` (first time)
28 | * `dotnet test`
29 |
30 | ### Success
31 |
32 | * All unit tests are green
33 | * All code has been converted to use the new syntax
34 |
35 | ### Solution
36 |
37 | The [solution branch](https://github.com/nickfloyd/csharp-seven-kata) has not been created yet.
38 |
39 | ### Additional reading on the new features in C# 7
40 |
41 | * [C# 7 Cheat Sheet](https://github.com/alugili/CSharp7Features/blob/master/C%237CheatSheet.pdf)
42 | * [What's new in C# 7](https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7)
43 | * [C# 7.0 Features - Stackoverflow](http://stackoverflow.com/documentation/c%23/1936/c-sharp-7-0-features#t=201703081541334596)
44 | * [.NET Framework - What's New in C# 7.0](https://msdn.microsoft.com/en-us/magazine/mt790184.aspx)
45 |
--------------------------------------------------------------------------------
/csharp-seven-kata-tests/AsyncReturnKataTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using csharp_seven_kata;
4 | using System.Threading.Tasks;
5 | using System.Diagnostics;
6 |
7 | namespace csharp_seven_kata_tests
8 | {
9 | [TestClass]
10 | public class AsyncReturnKataTests
11 | {
12 | [TestMethod]
13 | public async Task Validate_AsyncReturn()
14 | {
15 | var asyncReturnKata = new AsyncReturnKata();
16 |
17 | var sw = new Stopwatch();
18 |
19 | sw.Start();
20 | var result = await asyncReturnKata.ProcessWidget(1);
21 | sw.Stop();
22 |
23 | Debug.WriteLine($"Widget processed in {sw.ElapsedMilliseconds}ms");
24 | Assert.AreEqual(result, "Widget processed");
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/csharp-seven-kata-tests/ExpressionBodyKataTests.cs:
--------------------------------------------------------------------------------
1 | using csharp_seven_kata;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 |
4 | namespace csharp_seven_kata_tests
5 | {
6 | [TestClass]
7 | public class ExpressionBodyKataTests
8 | {
9 | [TestMethod]
10 | public void Validate_ExpressionBody()
11 | {
12 | var expressionBodyKata = new ExpressionBodyKata("Something");
13 |
14 | Assert.AreEqual("Something", expressionBodyKata.ExpressionBody);
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/csharp-seven-kata-tests/LocalFunctionsKataTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using csharp_seven_kata;
4 | using System.Collections.Generic;
5 |
6 | namespace csharp_seven_kata_tests
7 | {
8 | [TestClass]
9 | public class LocalFunctionsKataTests
10 | {
11 | [TestMethod]
12 | public void Validate_Local_Functions()
13 | {
14 | var localFunctionsKata = new LocalFunctionsKata();
15 |
16 | var widgets = localFunctionsKata.ManufactureWidgets();
17 |
18 | Assert.AreEqual(10, widgets.Count);
19 | }
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/csharp-seven-kata-tests/LocalReferencesKataTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using csharp_seven_kata;
4 |
5 | namespace csharp_seven_kata_tests
6 | {
7 | [TestClass]
8 | public class LocalReferencesKataTests
9 | {
10 | [TestMethod]
11 | public void Validate_Local_References()
12 | {
13 | const string message = "the more you know";
14 |
15 | var localReferencesKata = new LocalReferencesKata();
16 | localReferencesKata.SetMessage(message);
17 |
18 | var shootingStar = localReferencesKata.GetShootingStar();
19 | Assert.AreEqual(message, shootingStar.ToString());
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/csharp-seven-kata-tests/NumericLiteralSyntaxTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using csharp_seven_kata;
4 |
5 | namespace csharp_seven_kata_tests
6 | {
7 | [TestClass]
8 | public class NumericLiteralSyntaxTests
9 | {
10 | [TestMethod]
11 | public void Validate_Decimal_Formats()
12 | {
13 | Assert.AreEqual(0b00000001, NumericLiteralSyntax.OneDecimalFormat);
14 | Assert.AreEqual(0b00000010, NumericLiteralSyntax.TwoDecimalFormat);
15 | Assert.AreEqual(0b00000100, NumericLiteralSyntax.FourDecimalFormat);
16 | Assert.AreEqual(0b00001000, NumericLiteralSyntax.EightDecimalFormat);
17 | Assert.AreEqual(0b00010000, NumericLiteralSyntax.SixteenDecimalFormat);
18 | Assert.AreEqual(0b00100000, NumericLiteralSyntax.ThirtyTwoDecimalFormat);
19 | Assert.AreEqual(0b01000000, NumericLiteralSyntax.SixtyFourDecimalFormat);
20 | }
21 |
22 | [TestMethod]
23 | public void Validate_Hex_Formats()
24 | {
25 | Assert.AreEqual(0b00000001, NumericLiteralSyntax.OneHexFormat);
26 | Assert.AreEqual(0b00000010, NumericLiteralSyntax.TwoHexFormat);
27 | Assert.AreEqual(0b00000100, NumericLiteralSyntax.FourHexFormat);
28 | Assert.AreEqual(0b00001000, NumericLiteralSyntax.EightHexFormat);
29 | Assert.AreEqual(0b00010000, NumericLiteralSyntax.SixteenHexFormat);
30 | Assert.AreEqual(0b00100000, NumericLiteralSyntax.ThirtyTwoHexFormat);
31 | Assert.AreEqual(0b01000000, NumericLiteralSyntax.SixtyFourHexFormat);
32 | }
33 |
34 | [TestMethod]
35 | public void Validate_Bit_Shift_Formats()
36 | {
37 | Assert.AreEqual(0b00000001, NumericLiteralSyntax.OneBitShiftFormat);
38 | Assert.AreEqual(0b00000010, NumericLiteralSyntax.TwoBitShiftFormat);
39 | Assert.AreEqual(0b00000100, NumericLiteralSyntax.FourBitShiftFormat);
40 | Assert.AreEqual(0b00001000, NumericLiteralSyntax.EightBitShiftFormat);
41 | Assert.AreEqual(0b00010000, NumericLiteralSyntax.SixteenBitShiftFormat);
42 | Assert.AreEqual(0b00100000, NumericLiteralSyntax.ThirtyTwoBitShiftFormat);
43 | Assert.AreEqual(0b01000000, NumericLiteralSyntax.SixtyFourBitShiftFormat);
44 | }
45 |
46 | [TestMethod]
47 | public void Validate_Long_Max_Value()
48 | {
49 | Assert.AreEqual(long.MaxValue, NumericLiteralSyntax.LongMaxValue);
50 | }
51 |
52 | [TestMethod]
53 | public void Validate_OneMillionDollars()
54 | {
55 | Assert.AreEqual(1_000_000, NumericLiteralSyntax.OneMillionDollars);
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/csharp-seven-kata-tests/OutVariablesKataTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using csharp_seven_kata;
4 |
5 | namespace csharp_seven_kata_tests
6 | {
7 | [TestClass]
8 | public class OutVariablesKataTests
9 | {
10 | [TestMethod]
11 | public void Validate_Out_Varible()
12 | {
13 | var outVariablesKata = new OutVariablesKata();
14 | var result = outVariablesKata.ParseInteger("1");
15 |
16 | Assert.AreEqual(1, result);
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/csharp-seven-kata-tests/PatternMatchingKataTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using csharp_seven_kata;
4 |
5 | namespace csharp_seven_kata_tests
6 | {
7 | [TestClass]
8 | public class PatternMatchingKataTests
9 | {
10 | private PatternMatchingKata patternMatchingKata;
11 |
12 | [TestInitialize]
13 | public void Init() {
14 | patternMatchingKata = new PatternMatchingKata();
15 | }
16 |
17 | [TestMethod]
18 | public void Validate_IsExpression()
19 | {
20 | var result = patternMatchingKata.PatternMatchingIsExpression("Foo");
21 | Assert.AreEqual("FooBar", result);
22 |
23 | }
24 |
25 | [TestMethod]
26 | public void Validate_Switch_Matching()
27 | {
28 | var rebMoblin = new Moblin { Strength = 10, HitPoints = 25, Color = "Red" };
29 | var result = patternMatchingKata.PatternMatchingSwitch(rebMoblin);
30 |
31 | Assert.AreEqual("Red Moblin", result);
32 |
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/csharp-seven-kata-tests/ThrowExpressionsKataTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using csharp_seven_kata;
4 |
5 | namespace csharp_seven_kata_tests
6 | {
7 | [TestClass]
8 | public class ThrowExpressionsKataTests
9 | {
10 | [TestMethod]
11 | [ExpectedException(typeof(ArgumentNullException), "")]
12 | public void Validate_Property_Exception_Throw()
13 | {
14 | var throwExpressionsKata = new ThrowExpressionsKata()
15 | {
16 | PropertyException = null
17 | };
18 | }
19 |
20 | [TestMethod]
21 | [ExpectedException(typeof(ArgumentNullException), "")]
22 | public void Validate_Initialization_Exception_Throw()
23 | {
24 | var throwExpressionsKata = new ThrowExpressionsKata();
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/csharp-seven-kata-tests/TupleKataTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using csharp_seven_kata;
4 |
5 | namespace csharp_seven_kata_tests
6 | {
7 | [TestClass]
8 | public class TupleKataTests
9 | {
10 | [TestMethod]
11 | public void Validate_Multi_Returns_Method()
12 | {
13 | var tupleKata = new TupleKata();
14 |
15 | Assert.AreEqual(4, tupleKata.GetStringCount());
16 | Assert.AreEqual(3, tupleKata.GetIntCount());
17 |
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/csharp-seven-kata-tests/csharp-seven-kata-tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp1.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/csharp-seven-kata/AsyncReturnKata.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading.Tasks;
3 |
4 | namespace csharp_seven_kata
5 | {
6 | /*
7 | * From: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#generalized-async-return-types
8 | * Returning a Task object from async methods can introduce performance bottlenecks in certain paths.
9 | * Task is a reference type, so using it means allocating an object.
10 | *
11 | * In cases where a method declared with the async modifier returns a cached result, or completes synchronously,
12 | * the extra allocations can become a significant time cost in performance critical sections of code.
13 | * It can become very costly if those allocations occur in tight loops.
14 | *
15 | * The new language feature means that async methods may return other types in addition to Task, Task and void.
16 | * The returned type must still satisfy the async pattern, meaning a GetAwaiter method must be accessible.
17 | * As one concrete example, the ValueTask type has been added to the .NET framework to make use of this new language feature.
18 | */
19 |
20 | public class AsyncReturnKata
21 | {
22 | // KATA: Convert this method to use the new "ValueTask" syntax; specifically to use ValueTask
23 | // Note: You will need the System.Threading.Tasks.Extensions nuget package. ValueTask is not yet in C# 7
24 | // Note: Even in this contrived scenario, ValueTask should still be faster than Task
25 | // Note: In this method's current form it uses Heap allocation
26 |
27 | // Bonus: Duplicate the existing method, test and compare the timings of Task vs ValueTask
28 | public async Task ProcessWidget(int delay)
29 | {
30 | await Task.Delay(delay);
31 | return "Widget processed";
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/csharp-seven-kata/ExpressionBodyKata.cs:
--------------------------------------------------------------------------------
1 | namespace csharp_seven_kata
2 | {
3 | /*
4 | * From: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#more-expression-bodied-members
5 | * C# 6 introduced expression-bodied members for member functions, and read-only properties.
6 | * C# 7 expands the allowed members that can be implemented as expressions.
7 | * In C# 7, you can implement constructors, finalizers, and get and set accessors on properties and indexers.
8 | */
9 | public class ExpressionBodyKata
10 | {
11 | // KATA: Write the following property using the Expression-bodied get / set accessors syntax
12 | private string expressionBody;
13 | public string ExpressionBody {
14 | get {
15 | return expressionBody;
16 | }
17 | set {
18 | expressionBody = value;
19 | }
20 | }
21 |
22 | // KATA: Write the following constructor using the Expression-bodied syntax
23 | public ExpressionBodyKata(string expressionBody) {
24 | ExpressionBody = expressionBody;
25 | }
26 |
27 | // KATA: Write the following property using the Expression-bodied finalizer
28 | // Note: It should be called out that this class does not need or should implement a finalizer (destructor) but for the kata one has been added
29 | ~ExpressionBodyKata() {
30 | expressionBody = null;
31 | }
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/csharp-seven-kata/LocalFunctionsKata.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 |
5 | namespace csharp_seven_kata
6 | {
7 |
8 | /*
9 | * From: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#local-functions
10 | * Many designs for classes include methods that are called from only one location.
11 | * These additional private methods keep each method small and focused.
12 | * However, they can make it harder to understand a class when reading it the first time.
13 | * These methods must be understood outside of the context of the single calling location.
14 | *
15 | * For those designs, local functions enable you to declare methods inside the context of another method.
16 | * This makes it easier for readers of the class to see that the local method is only called from the context in which is it declared.
17 | *
18 | * There are two very common use cases for local functions: public iterator methods and public async methods.
19 | * Both types of methods generate code that reports errors later than programmers might expect.
20 | * In the case of iterator methods, any exceptions are observed only when calling code that enumerates the returned sequence.
21 | * In the case of async methods, any exceptions are only observed when the returned Task is awaited.
22 | */
23 | public class LocalFunctionsKata
24 | {
25 | // KATA: Collapse ManufactureWidgets, BuildWidget, and GenerateWidgetName all into a single method with local functions.
26 | // Note: Make sure to nest according to scope and use
27 |
28 | public List ManufactureWidgets() {
29 |
30 | var widgets = new List();
31 |
32 | for (int i = 0; i < 10; i++)
33 | {
34 | widgets.Add(BuildWidget(i, $"Widget{i}"));
35 | }
36 |
37 | return widgets;
38 | }
39 |
40 | private Widget BuildWidget(int id, string name) {
41 | var newName = GenerateWidgetName(name);
42 | return new Widget { Id = id, Name = newName };
43 | }
44 |
45 | private string GenerateWidgetName(string name) {
46 | var random = new Random();
47 | var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
48 | return new string(
49 | Enumerable.Repeat(chars, name.Length)
50 | .Select(s => s[random.Next(s.Length)]).ToArray()
51 | );
52 | }
53 | }
54 |
55 | public class Widget {
56 | public int Id { get; set; }
57 | public string Name { get; set; }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/csharp-seven-kata/LocalReferencesKata.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace csharp_seven_kata
4 | {
5 | /*
6 | * From: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#ref-locals-and-returns
7 | * This feature enables algorithms that use and return references to variables defined elsewhere.
8 | * These are useful for changing and returning references to specific memory instead of copying memory.
9 | *
10 | * Avoiding the overhead of copying resources or pinning memory can be benefitial for high performance applications.
11 | */
12 | public class LocalReferencesKata
13 | {
14 | //KATA: Use the ref feature to set the message on _shootingStar without using _shootingStar.SetMessage(message).
15 | //_shootingStar.GetMessageByRef() has been provided as a starting point. Modify GetMessageByRef() to return a
16 | //reference to _message that can be assigned from LocalReferencesKata.SetMessage().
17 | public void SetMessage(string message)
18 | {
19 | _shootingStar.SetMessage(message);
20 | }
21 |
22 | private ShootingStar _shootingStar;
23 |
24 | public LocalReferencesKata()
25 | {
26 | _shootingStar = new ShootingStar();
27 | }
28 |
29 | public ShootingStar GetShootingStar()
30 | {
31 | return _shootingStar;
32 | }
33 | }
34 |
35 | public class ShootingStar
36 | {
37 | private string _message;
38 |
39 | public string GetMessageByRef()
40 | {
41 | return _message;
42 | }
43 |
44 | public void SetMessage(string message)
45 | {
46 | _message = message;
47 | }
48 |
49 | public override string ToString()
50 | {
51 | return _message;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/csharp-seven-kata/NumericLiteralSyntaxKata.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace csharp_seven_kata
4 | {
5 | /*
6 | * From: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#numeric-literal-syntax-improvements
7 | * Misreading numeric constants can make it harder to understand code when reading it for the first time.
8 | * This often occurs when those numbers are used as bit masks or other symbolic rather than numeric values.
9 | * C# 7 includes two new features to make it easier to write numbers in the most readable fashion for the intended use: binary literals, and digit separators.
10 | * For those times when you are creating bit masks, or whenever a binary representation of a number makes the most readable code, write that number in binary.
11 | */
12 | public class NumericLiteralSyntax
13 | {
14 | // KATA: Write the following ints from their respective format to a binary literal format
15 | // Note: Make sure to use the '0b' at the beginning of the constant value
16 | // Note: The digit separator can be used with decimal, float and double types
17 |
18 | public const int OneDecimalFormat = 1;
19 | public const int TwoDecimalFormat = 2;
20 | public const int FourDecimalFormat = 4;
21 | public const int EightDecimalFormat = 8;
22 | public const int SixteenDecimalFormat = 16;
23 | public const int ThirtyTwoDecimalFormat = 32;
24 | public const int SixtyFourDecimalFormat = 64;
25 |
26 | public const int OneHexFormat = 0x01;
27 | public const int TwoHexFormat = 0x02;
28 | public const int FourHexFormat = 0x04;
29 | public const int EightHexFormat = 0x08;
30 | public const int SixteenHexFormat = 0x10;
31 | public const int ThirtyTwoHexFormat = 0x20;
32 | public const int SixtyFourHexFormat = 0x40;
33 |
34 | public const int OneBitShiftFormat = 1 << 0;
35 | public const int TwoBitShiftFormat = 1 << 1;
36 | public const int FourBitShiftFormat = 1 << 2;
37 | public const int EightBitShiftFormat = 1 << 3;
38 | public const int SixteenBitShiftFormat = 1 << 4;
39 | public const int ThirtyTwoBitShiftFormat = 1 << 5;
40 | public const int SixtyFourBitShiftFormat = 1 << 6;
41 |
42 | // KATA: Convert the long.MaxValue to a decimal representation using the "digit separator"
43 | public const long LongMaxValue = long.MaxValue; //9,223,372,036,854,775,807
44 |
45 | // KATA: Convert the 100000000 to a decimal representation using the "digit separator"
46 | public const int OneMillionDollars = 1000000;
47 |
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/csharp-seven-kata/OutVariablesKata.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace csharp_seven_kata
4 | {
5 | /*
6 | * From: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#out-variables
7 | * Previously, you would need to separate the declaration of the out variable and its initialization into two different statements.
8 | * You can now declare out variables in the argument list of a method call, rather than writing a separate declaration statement.
9 | */
10 | public class OutVariablesKata
11 | {
12 | // KATA: Convert the method body to use an inline out varible
13 | // Note: When declaring the inline out varible you can use either an implicit (var) or explicit (int) type
14 | public int ParseInteger(string val) {
15 | int parsedInt;
16 |
17 | if (!int.TryParse(val, out parsedInt))
18 | {
19 | parsedInt = int.MinValue;
20 | }
21 |
22 | return parsedInt;
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/csharp-seven-kata/PatternMatchingKata.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace csharp_seven_kata
4 | {
5 | /*
6 | * From: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#pattern-matching
7 | * Pattern matching is a feature that allows you to implement method dispatch on properties other than the type of an object.
8 | * You're probably already familiar with method dispatch based on the type of an object.
9 | * In Object Oriented programming, virtual and override methods provide language syntax to implement method dispatching based on an object's type.
10 | * Base and Derived classes provide different implementations. Pattern matching expressions extend this concept so that
11 | * you can easily implement similar dispatch patterns for types and data elements that are not related through an inheritance hierarchy.
12 | *
13 | * Pattern matching supports is expressions and switch expressions.
14 | * Each enables inspecting an object and its properties to determine if that object satisfies the sought pattern.
15 | * You use the when keyword to specify additional rules to the pattern.
16 | */
17 | public class PatternMatchingKata
18 | {
19 |
20 | // KATA: Replace the "as" convention and null check with the "is" syntax
21 | // Note: Should be able to accomplish without the use of "as," "ToString()," "switch" or casting.
22 | public string PatternMatchingIsExpression(object val) {
23 |
24 | var str = val as string;
25 |
26 | if (str != null) {
27 | str += "Bar";
28 | }
29 |
30 | return str;
31 |
32 | }
33 |
34 | // KATA: Replace the conditional statement under the Moblin case with 2 separate cases where one uses
35 | // pattern matching to check to see if the color on the Moblin is "Red"
36 | public string PatternMatchingSwitch(ICreature creature) {
37 |
38 | var creatureName = string.Empty;
39 |
40 | switch (creature) {
41 | case Chuchu c:
42 | creatureName = "Chuchu";
43 | break;
44 | case Octorok o:
45 | creatureName = "Octorok";
46 | break;
47 | case Moblin m:
48 | if (m.Color == "Red")
49 | {
50 | creatureName = "Red Moblin";
51 | }
52 | else {
53 | creatureName = "Moblin";
54 | }
55 | break;
56 | default:
57 | creatureName = "Unknown Creature";
58 | break;
59 |
60 | }
61 |
62 | return creatureName;
63 |
64 |
65 | }
66 |
67 | }
68 |
69 | public interface ICreature {}
70 |
71 | public class Creature : ICreature {}
72 |
73 | public class Chuchu : Creature
74 | {
75 | public int Strength { get; set; }
76 | public int HitPoints { get; set; }
77 |
78 | }
79 |
80 | public class Octorok : Creature
81 | {
82 | public int Strength { get; set; }
83 | public int HitPoints { get; set; }
84 | }
85 |
86 | public class Moblin : Creature
87 | {
88 | public int Strength { get; set; }
89 | public int HitPoints { get; set; }
90 | public string Color { get; set; }
91 | }
92 |
93 |
94 | }
95 |
--------------------------------------------------------------------------------
/csharp-seven-kata/ThrowExpressionsKata.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace csharp_seven_kata
4 | {
5 | /*
6 | * From: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#throw-expressions
7 | * In C#, throw has always been a statement. Because throw is a statement, not an expression, there were C# constructs where you could not use it.
8 | * These included conditional expressions, null coalescing expressions, and some lambda expressions.
9 | * The addition of expression-bodied members adds more locations where throw expressions would be useful.
10 | * So that you can write any of these constructs, C# 7 introduces throw expressions.
11 | *
12 | * The syntax is the same as you've always used for throw statements.
13 | * The only difference is that now you can place them in new locations, such as in a conditional expression.
14 | */
15 | public class ThrowExpressionsKata
16 | {
17 | // KATA: Take this assignment out of the constructor and throw an error when Settings is initialized to null
18 | // Hint: You should be able to remove the null check from the constructor
19 | // Hint: You should be able to move the initialization logic from the setter on the property to the private and use an expression body to initialize and throw if null
20 | // Note: Doing exceptions this way will cause exceptions to be thrown during the construction of an object. This is generally discouraged.
21 | public ThrowExpressionsKata() {
22 | if (Settings == null) {
23 | throw new ArgumentNullException("Could not load settings");
24 | }
25 | }
26 |
27 |
28 | private ISettings settings;
29 | public ISettings Settings { get => settings; set => settings = InitializeSettings(); }
30 |
31 | // KATA: Replace the conditional in the setter with an expression-body (see the getter) and a throw expression
32 | // Making the setter a single line of code.
33 | // Hint: you can use the null coalese
34 | // Note: Doing exceptions this way will cause exceptions to be thrown during the construction of an object. This is generally discouraged.
35 | private string propertyException = "Default";
36 | public string PropertyException
37 | {
38 | get => propertyException;
39 | set
40 | {
41 | if (value != null)
42 | {
43 | propertyException = value;
44 | }
45 | else {
46 | throw new ArgumentNullException("Cannot assign null");
47 | }
48 | }
49 | }
50 |
51 | private ISettings InitializeSettings() {
52 | return null;
53 | }
54 |
55 | }
56 |
57 | public interface ISettings {
58 | int Id { get; set; }
59 | string Name { get; set; }
60 | }
61 |
62 | public class Settings : ISettings {
63 | public int Id { get; set; }
64 | public string Name { get; set; }
65 | }
66 |
67 | }
68 |
69 |
--------------------------------------------------------------------------------
/csharp-seven-kata/TupleKata.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace csharp_seven_kata
4 | {
5 | /*
6 | * From: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#tuples
7 | * C# provides a rich syntax for classes and structs that is used to explain your design intent.
8 | * But sometimes that rich syntax requires extra work with minimal benefit.
9 | * You may often write methods that need a simple structure containing more than one data element.
10 | * To support these scenarios tuples were added to C#.
11 | * Tuples are lightweight data structures that contain multiple fields to represent the data members.
12 | * The fields are not validated, and you cannot define your own methods.
13 | */
14 |
15 | /*
16 | * The primary reason for introduction of ValueTuple is performance.
17 | *
18 | * Differences between ValueTuple and Tuple:
19 | *
20 | * [ValueTuple] [Tuple]
21 | * Class or structure struct class
22 | * Mutability mutable immutable
23 | * Naming members yes no (TBD)
24 | */
25 |
26 |
27 | // Note: You will need the System.ValueTuple nuget package to complete this kata
28 | // https://www.nuget.org/packages/System.ValueTuple/
29 | public class TupleKata
30 | {
31 |
32 | // KATA: Convert the two methods below to one method that returns a ValueTuple (int StringCount, int IntCount).
33 | // Modify the unit test to validate the values from the new tuple.
34 | private string[] StringArr= new string[] { "one", "two", "three", "four"};
35 | private int[] IntArr = new int[] {1,2,3};
36 |
37 | public int GetStringCount() {
38 | return StringArr.Length;
39 | }
40 |
41 | public int GetIntCount()
42 | {
43 | return IntArr.Length;
44 | }
45 |
46 |
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/csharp-seven-kata/csharp-seven-kata.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard1.4
5 |
6 |
7 |
--------------------------------------------------------------------------------
/csharp-seven-kata/csharp-seven-kata.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.26228.4
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "csharp-seven-kata", "csharp-seven-kata.csproj", "{546485FB-64DA-4F34-B26C-493F93854273}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "csharp-seven-kata-tests", "..\csharp-seven-kata-tests\csharp-seven-kata-tests.csproj", "{70D9DA06-F8BC-47F0-8359-CE86E8F10251}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {546485FB-64DA-4F34-B26C-493F93854273}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {546485FB-64DA-4F34-B26C-493F93854273}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {546485FB-64DA-4F34-B26C-493F93854273}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {546485FB-64DA-4F34-B26C-493F93854273}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {70D9DA06-F8BC-47F0-8359-CE86E8F10251}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {70D9DA06-F8BC-47F0-8359-CE86E8F10251}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {70D9DA06-F8BC-47F0-8359-CE86E8F10251}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {70D9DA06-F8BC-47F0-8359-CE86E8F10251}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | EndGlobal
29 |
--------------------------------------------------------------------------------