├── .gitignore
├── LICENSE
├── README.md
├── Src
├── TheCSharp.sln
└── TheCSharp
│ ├── Anonymous
│ ├── Anonymous.png
│ ├── AnonymousMethod.cs
│ ├── AnonymousMethodTest.cs
│ ├── AnonymousType.cs
│ ├── AnonymousTypeTest.cs
│ └── Readme.txt
│ ├── Async
│ ├── AsyncAwait.png
│ ├── AsyncClass.cs
│ ├── AsyncClassTest.cs
│ └── ReadMe.txt
│ ├── DataStructure
│ ├── DataStrcuture.cs
│ ├── DataStructureTest.cs
│ ├── Datastructure.png
│ └── ReadMe.txt
│ ├── Delegate
│ ├── Delegate.png
│ ├── DelegateClass.cs
│ ├── DelegateClassTest.cs
│ ├── MulticastDelegateClass.cs
│ ├── MulticastDelegateClassTest.cs
│ └── ReadMe.txt
│ ├── DynamicType
│ ├── DynamicType.cs
│ ├── DynamicTypeTest.cs
│ ├── ReadMe.txt
│ └── dynamictype.png
│ ├── Events
│ ├── EventClass.cs
│ ├── EventClassTest.cs
│ ├── Events.JPG
│ └── ReadMe.txt
│ ├── ExceptionHandling
│ ├── Exception.png
│ ├── ExceptionHander.cs
│ ├── ExceptionHanderTest.cs
│ └── ReadMe.txt
│ ├── ExpressionTree
│ ├── ExpressionTree.cs
│ ├── ExpressionTree.png
│ ├── ExpressionTreeTest.cs
│ └── ReadMe.txt
│ ├── ExtensionMethod
│ ├── ExtensionMethod.png
│ ├── ExtenstionMethod.cs
│ ├── ExtentionMethodTest.cs
│ └── ReadMe.txt
│ ├── Generic
│ ├── Generic.cs
│ ├── GenericTest.cs
│ ├── Generics.png
│ └── ReadMe.txt
│ ├── Indexer
│ ├── Indexer.cs
│ ├── Indexer.png
│ ├── IndexerTest.cs
│ └── ReadMe.txt
│ ├── LambdaExpression
│ ├── LambdaExpression.cs
│ ├── LambdaExpression.png
│ ├── LambdaExpressionTest.cs
│ └── ReadMe.txt
│ ├── Linq
│ ├── Linq.cs
│ ├── Linq.png
│ ├── LinqTest.cs
│ └── ReadMe.txt
│ ├── Nullable
│ ├── Nullable.png
│ ├── NullableClass.cs
│ ├── NullableClassTest.cs
│ └── ReadMe.txt
│ ├── OperatorOverloading
│ ├── OperatorOverloading.cs
│ ├── OperatorOverloading.png
│ ├── OperatorOverloadingTest.cs
│ └── ReadMe.txt
│ ├── Parallel
│ ├── Parallel.png
│ ├── ParallelClass.cs
│ ├── ParallelClassTest.cs
│ └── ReadMe.txt
│ ├── Partial
│ ├── Partial.png
│ ├── PartialClassTest.cs
│ ├── PartialFile1.cs
│ ├── PartialFile2.cs
│ ├── PartialMethod1.cs
│ ├── PartialMethod2.cs
│ ├── PartialMethodTest.cs
│ └── ReadMe.txt
│ ├── PatternMatching
│ ├── PatternMatching.cs
│ ├── PatternMatchingTest.cs
│ └── ReadMe.txt
│ └── TheCSharp.csproj
└── docs
├── dt.png
├── f1.png
├── f2.JPG
├── fu.jpg
├── his.png
├── logo.png
└── others.gif
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 s. m. ahasan habib
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 | # TheCSharp
2 |
3 | * C# is modern, object oriented, typesafe programming language thats popularaties are incresing day by day.
4 | * This language is approved European Computer Manufactures Association (ECMA) and International standard organization (ISO).
5 | * It is C family language. Other memebers are (C++, Java)
6 | * Its features are added regularly and current day it becomes one of the most popular programming language.
7 |
8 |
9 |
10 | ## History
11 |
12 | * The language is invented by Microsoft at 2002 and shifted with .NET framework.
13 | * Anders Hejlsberg is the guy who designed C#
14 |
15 | 
16 |
17 |
18 |
19 | ## Data types
20 |
21 | C# is typesafe language. It has many datatypes.
22 |
23 | 
24 |
25 |
26 |
27 | ## Features
28 |
29 | So many features are available now. But not all features come to its born time. Gradually C# team improve its features.
30 |
31 | 
32 |
33 |
34 | ## Features like other popular languages
35 |
36 | Many C# features are borrowed from other popular languages like C++, Java etc.
37 |
38 | 
39 |
40 |
41 |
42 |
43 | ## All interesting CSharp language features are demonastrated:
44 |
45 | * Anonymous Type/Function
46 | * Delegate (SingleCast/Multicast)
47 | * Asynchonous/Parallel Programming
48 | * Builtin Datastrcutures (Array, List, Stack, Queue, Linklist, Dictionary, Set etc.)
49 | * Partial Class/Method
50 | * Exception Handling
51 | * Dynamic
52 | * Linq/Lambda Expression/Expression Tree
53 | * Generics (CoVariance/ContraVariance)
54 | * Pattern Matching
55 | * and more...
56 |
57 | #### Few c# features are described [here](https://www.codeproject.com/Articles/696879/Sexy-Csharp)
58 |
59 |
--------------------------------------------------------------------------------
/Src/TheCSharp.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29613.14
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheCSharp", "TheCSharp\TheCSharp.csproj", "{9C3DEA8D-31AD-4D5D-82DB-81EC83EE95C2}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {9C3DEA8D-31AD-4D5D-82DB-81EC83EE95C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {9C3DEA8D-31AD-4D5D-82DB-81EC83EE95C2}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {9C3DEA8D-31AD-4D5D-82DB-81EC83EE95C2}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {9C3DEA8D-31AD-4D5D-82DB-81EC83EE95C2}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {C99EF168-9FA3-498A-8835-1C64E96D06C0}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Anonymous/Anonymous.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/Anonymous/Anonymous.png
--------------------------------------------------------------------------------
/Src/TheCSharp/Anonymous/AnonymousMethod.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.Anonymous
6 | {
7 | ///
8 | /// A custom class to implement/show anonymous method
9 | ///
10 | public class AnonymousMethod
11 | {
12 | private delegate int AddDelegate(int x, int y);
13 |
14 | ///
15 | /// Add 2 variables using anonymous method.
16 | ///
17 | ///
18 | ///
19 | ///
20 | public int Add(int x, int y)
21 | {
22 | AddDelegate add = delegate (int x, int y)
23 | {
24 | return x + y;
25 | };
26 |
27 | return add(x, y);
28 | }
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Anonymous/AnonymousMethodTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.Anonymous
8 | {
9 | public class AnonymousMethodTest
10 | {
11 | private readonly AnonymousMethod anonymousMethod = new AnonymousMethod();
12 |
13 | [Fact]
14 | public void ShouldReturnSumWhenXandYValueProvided()
15 | {
16 | int x = 20;
17 | int y = 10;
18 | int z = anonymousMethod.Add(x, y);
19 |
20 | z.Should().Be(30);
21 | }
22 |
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Anonymous/AnonymousType.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.Anonymous
6 | {
7 | ///
8 | /// A custom class to show Anonymous Type
9 | ///
10 | public class AnonymousType
11 | {
12 | ///
13 | /// A anonymous type
14 | ///
15 | /// a student with 2 properties Id & Name
16 | public object CreateAnonymousStudent(string id, string name)
17 | {
18 | var student = new
19 | {
20 | Id = id,
21 | Name = name
22 | };
23 |
24 | return student;
25 | }
26 |
27 | public int ExtractAnonymousStudentId(object student)
28 | {
29 | dynamic studentLocal = student;
30 |
31 | int studentId = studentLocal.Id;
32 |
33 | return studentId;
34 | }
35 |
36 | public int ExtractAnonymousStudentIdV2(object student)
37 | {
38 | object studentId = student.GetType().GetProperty("Id").GetValue(student);
39 |
40 | return (int)studentId;
41 | }
42 |
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Anonymous/AnonymousTypeTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.Anonymous
8 | {
9 | public class AnonymousTypeTest
10 | {
11 | private readonly AnonymousType anonymousType = new AnonymousType();
12 |
13 | [Fact]
14 | public void ShouldReturnStudentAnonymousType()
15 | {
16 | var student = anonymousType.CreateAnonymousStudent("1", "Student-1");
17 |
18 | student.Should().NotBeNull();
19 | }
20 |
21 | [Fact]
22 | public void ShuoldReturnStudentAnonymousTypeId()
23 | {
24 | var student = new { Id = 100, Name = "Student-100" };
25 |
26 | int studentId = anonymousType.ExtractAnonymousStudentId(student);
27 |
28 | studentId.Should().Be(100);
29 | }
30 |
31 | [Fact]
32 | public void ShuoldReturnStudentAnonymousTypeIdV2()
33 | {
34 | var student = new { Id = 100, Name = "Student-100" };
35 |
36 | int studentId = anonymousType.ExtractAnonymousStudentIdV2(student);
37 |
38 | studentId.Should().Be(100);
39 | }
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Anonymous/Readme.txt:
--------------------------------------------------------------------------------
1 | ###########################################################################
2 |
3 | # AnonymousType feature is introduced from C# version 3
4 |
5 | # Anymonyous means which does not have name.
6 |
7 | # C# has 2 anonymous features
8 | 1) Anonymous Type : A type without a name.
9 | 2) AnonymousMethod : A method without a name.
10 |
11 | ###########################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/Async/AsyncAwait.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/Async/AsyncAwait.png
--------------------------------------------------------------------------------
/Src/TheCSharp/Async/AsyncClass.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Text;
5 | using System.Threading;
6 | using System.Threading.Tasks;
7 |
8 | namespace TheCSharp.Async
9 | {
10 | ///
11 | /// Demonastrate Async features
12 | ///
13 | public class AsyncClass
14 | {
15 | ///
16 | /// 3 seconds needed to complete this
17 | ///
18 | ///
19 | public Task Process1Async()
20 | {
21 | Task task = Task.Delay(3000); // does not block the current thread
22 |
23 | return task;
24 | }
25 |
26 | ///
27 | /// 4 seconds needed to complete this
28 | ///
29 | ///
30 | public Task Process2Async()
31 | {
32 | Task task = Task.Delay(4000); // does not block the current thread
33 |
34 | return task;
35 | }
36 |
37 | ///
38 | /// Execute Synchonous Method Asynchonously
39 | ///
40 | ///
41 | public Task ExecuteAsync()
42 | {
43 | var action = new Action(VisitIntegerNumbers);
44 |
45 | var task = new Task(action);
46 | task.Start();
47 |
48 | return task;
49 | }
50 |
51 | public Task ExecutewithCancelSupportAsync()
52 | {
53 | var cancelSource = new CancellationTokenSource();
54 | var token = cancelSource.Token;
55 |
56 | Task task = Task.Run(() =>
57 | {
58 | LongRunningOperation(token);
59 | });
60 |
61 |
62 | // send signal to cancel execution
63 | cancelSource.Cancel();
64 |
65 | return task;
66 | }
67 |
68 | ///
69 | /// Dummy processing
70 | ///
71 | private void VisitIntegerNumbers()
72 | {
73 | for (int i = 0; i < int.MaxValue; i++)
74 | {
75 | }
76 | Debug.Write($"Completed visited upto {int.MaxValue - 1}");
77 | }
78 |
79 | private void LongRunningOperation(CancellationToken token)
80 | {
81 | for (int i = 0; i < int.MaxValue; i++)
82 | {
83 | if (token.IsCancellationRequested)
84 | {
85 | token.ThrowIfCancellationRequested();
86 | }
87 | }
88 | Debug.Write($"Completed counting {int.MaxValue} sequentially!");
89 | }
90 | }
91 |
92 | }
93 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Async/AsyncClassTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.Text;
6 | using System.Threading;
7 | using System.Threading.Tasks;
8 | using Xunit;
9 |
10 | namespace TheCSharp.Async
11 | {
12 | public class AsyncClassTest
13 | {
14 | private readonly AsyncClass asyncObject = new AsyncClass();
15 |
16 | [Fact]
17 | public Task ProcessAsynchronously()
18 | {
19 | Task task1 = asyncObject.Process1Async();
20 | Countring();
21 | Task task2 = asyncObject.Process2Async();
22 | Countring();
23 |
24 | Task.WaitAll(task1, task2); // block the thread untill finish all the executions
25 |
26 | return Task.CompletedTask;
27 | }
28 |
29 | [Fact]
30 | public Task ShouldExecuteSyncMethodAsynchronously()
31 | {
32 | Task task = asyncObject.ExecuteAsync();
33 |
34 | task.Wait();
35 |
36 | return Task.CompletedTask;
37 | }
38 |
39 | [Fact]
40 | public async Task ShouldCancelCurrentAsynchonousExecution()
41 | {
42 | await Assert.ThrowsAsync(asyncObject.ExecutewithCancelSupportAsync);
43 | }
44 |
45 | private void Countring()
46 | {
47 | for (int i = 0; i < int.MaxValue; i++)
48 | {
49 | }
50 | Debug.WriteLine($"counting completed from 0 to {int.MaxValue - 1}");
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Async/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ###########################################################################
2 |
3 | # Task class represent single operation and execute asynchonously
4 |
5 | # Task is the central object of Task based asynchonous pattern
6 |
7 | # It supports cancelation during execution
8 |
9 | # It is possible to execute synchonous to asynchonous fashon and vise versa
10 |
11 | ###########################################################################
12 |
--------------------------------------------------------------------------------
/Src/TheCSharp/DataStructure/DataStrcuture.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Text;
5 | using System.Linq;
6 |
7 | namespace TheCSharp.DataStructure
8 | {
9 | public class DataStrcuture
10 | {
11 | public void Array()
12 | {
13 | var rollNumbers = new int[4] { 1, 2, 3, 4 };
14 |
15 | int rollNumberLength = rollNumbers.Length;
16 |
17 | // array update
18 | rollNumbers.SetValue(100, 0); // set 100 to 0 index
19 |
20 | // array traversal
21 | for (int index = 0; index < rollNumbers.Length; index++)
22 | {
23 | Debug.Write($"{rollNumbers[index]}");
24 | }
25 |
26 | // access index item
27 | int roll = rollNumbers[1];
28 |
29 | }
30 |
31 | public void List()
32 | {
33 | // declare and assign
34 | var rollNumberList = new List(3) { 1, 2, 3 };
35 |
36 | // traversal
37 | foreach (int roll in rollNumberList)
38 | {
39 | Debug.Write($"{roll}");
40 | }
41 |
42 | // access a particular item
43 | int rollNumber = rollNumberList[1];
44 |
45 | // added item dynamically
46 | rollNumberList.Add(4);
47 |
48 | // remove a particular item
49 | rollNumberList.Remove(1);
50 |
51 | // existence check
52 | bool exists = rollNumberList.Contains(2);
53 | }
54 |
55 | public void HashTable()
56 | {
57 | // declare and initialize
58 | var dictionary = new Dictionary(3) { { 1, "A" }, { 2, "B" }, { 3, "C" } };
59 |
60 | // accessing first item
61 | string istItem = dictionary[1];
62 |
63 | // traversal
64 | foreach (KeyValuePair item in dictionary)
65 | {
66 | Debug.WriteLine($"Key={item.Key} Value={item.Value}");
67 | }
68 |
69 | // adding new item
70 | dictionary.Add(4, "D");
71 |
72 | // remove a particular item
73 | dictionary.Remove(1);
74 | }
75 |
76 | public void HashSet()
77 | {
78 | var set = new HashSet();
79 |
80 | // adding item. ignore duplicate values.
81 | set.Add(1);
82 | set.Add(1);
83 | set.Add(2);
84 |
85 | // remove a particular item
86 | set.Remove(1);
87 |
88 | // traversal
89 | foreach (int item in set)
90 | {
91 | Debug.Write($"item");
92 | }
93 | }
94 |
95 | public void Stack()
96 | {
97 | // declaration
98 | var stack = new Stack(3);
99 |
100 | // adding
101 | stack.Push(1);
102 | stack.Push(2);
103 |
104 | // feching lastly inserted (with removing from stack)
105 | int item = stack.Pop();
106 |
107 | // fetching lastly inserted item without removing from stack
108 | int nextItem = stack.Peek();
109 |
110 | int totalItems = stack.Count();
111 | }
112 |
113 | public void Queue()
114 | {
115 | var queue = new Queue(3);
116 |
117 | //adding
118 | queue.Enqueue(1);
119 | queue.Enqueue(2);
120 |
121 | // feching with removing first item from queue
122 | int item = queue.Dequeue();
123 |
124 | //feching without removing first item from queue
125 | int item2 = queue.Peek();
126 |
127 | int totalItems = queue.Count();
128 | }
129 |
130 | public void LinkList()
131 | {
132 | // declaring
133 | var linkList = new LinkedList();
134 |
135 | // adding item
136 | linkList.AddLast(1);
137 | linkList.AddLast(2);
138 | linkList.AddFirst(3);
139 | linkList.AddFirst(4);
140 |
141 | // removing item
142 | linkList.RemoveLast();
143 | linkList.Remove(1);
144 | linkList.RemoveFirst();
145 |
146 | // checking item existence
147 | bool found = linkList.Contains(1);
148 |
149 | // traversing
150 | foreach (int item in linkList)
151 | {
152 | Debug.Write(item);
153 | }
154 | }
155 |
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/Src/TheCSharp/DataStructure/DataStructureTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using Xunit;
5 |
6 | namespace TheCSharp.DataStructure
7 | {
8 | public class DataStructureTest
9 | {
10 | private readonly DataStrcuture dataStructure = new DataStrcuture();
11 |
12 | [Fact]
13 | public void ArrayTest()
14 | {
15 | dataStructure.Array();
16 | }
17 |
18 | [Fact]
19 | public void ListTest()
20 | {
21 | dataStructure.List();
22 | }
23 |
24 | [Fact]
25 | public void HashTableTest()
26 | {
27 | dataStructure.HashTable();
28 | }
29 |
30 | [Fact]
31 | public void HashSetTest()
32 | {
33 | dataStructure.HashSet();
34 | }
35 |
36 | [Fact]
37 | public void StackTest()
38 | {
39 | dataStructure.Stack();
40 | }
41 |
42 | [Fact]
43 | public void QueueTest()
44 | {
45 | dataStructure.Queue();
46 | }
47 |
48 | [Fact]
49 | public void LinkListTest()
50 | {
51 | dataStructure.LinkList();
52 | }
53 |
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Src/TheCSharp/DataStructure/Datastructure.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/DataStructure/Datastructure.png
--------------------------------------------------------------------------------
/Src/TheCSharp/DataStructure/ReadMe.txt:
--------------------------------------------------------------------------------
1 | #######################################################################################################
2 |
3 | # For efficent algorithm implementation, relevant datastructure is prerequisit.
4 |
5 | # Every programing language has built in data structures .
6 |
7 | # C# has various builtin data structures
8 | i) Array
9 | ii) List
10 | iii) Map/Set/Dictioray
11 | iv) LinkList
12 | v) Stack
13 | vi) Quieue
14 |
15 |
16 | # I have a diffent github repository to know and check in details about datastructures in programming.
17 |
18 | #######################################################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/Delegate/Delegate.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/Delegate/Delegate.png
--------------------------------------------------------------------------------
/Src/TheCSharp/Delegate/DelegateClass.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.Delegate
6 | {
7 | public class DelegateClass
8 | {
9 | private delegate int GetTotalSalary();
10 |
11 | public int GetTotalSalaryAmount(int employeeType)
12 | {
13 | GetTotalSalary getTotalSalary = null;
14 |
15 | if (employeeType == 0) //consultant
16 | {
17 | getTotalSalary = GetConsultantsTotalSalary;
18 | }
19 | else if (employeeType == 1) //director
20 | {
21 | getTotalSalary = GetDirectorsTotalSalary;
22 | }
23 | else if (employeeType == 20) //general employee
24 | {
25 | getTotalSalary = GetEmployeesTotalSalary;
26 | }
27 | else
28 | {
29 | throw new ApplicationException("Sorry! Not a valid employee type.");
30 | }
31 |
32 | int totalSalaryAmount = getTotalSalary();
33 |
34 | return totalSalaryAmount;
35 | }
36 |
37 | ///
38 | /// Using built in delegate Funct where last type is return type
39 | /// Another buitin deleage Action but it does not return any value
40 | ///
41 | ///
42 | ///
43 | public int GetTotalSalaryAmountUsingFuncBuitinDelegate(int employeeType)
44 | {
45 | // last generic type of Func is always return type
46 | Func getTotalSalaryIncludingTax = null;
47 |
48 | if (employeeType == 1) //consultant
49 | {
50 | getTotalSalaryIncludingTax = GetConsultantsTotalSalaryWithTax;
51 | }
52 | else if (employeeType == 2) //general employee
53 | {
54 | getTotalSalaryIncludingTax = GetDirectorsTotalSalaryWithTax;
55 | }
56 | else
57 | {
58 | throw new ApplicationException("Sorry! Not a valid employee type.");
59 | }
60 |
61 | var taxPercent = (decimal).10;
62 | int totalSalaryAmount = getTotalSalaryIncludingTax(taxPercent);
63 |
64 | return totalSalaryAmount;
65 | }
66 |
67 | private int GetConsultantsTotalSalary()
68 | {
69 | return 200;
70 | }
71 |
72 | private int GetEmployeesTotalSalary()
73 | {
74 | return 100;
75 | }
76 |
77 | private int GetDirectorsTotalSalary()
78 | {
79 | return 300;
80 | }
81 |
82 | private int GetConsultantsTotalSalaryWithTax(decimal taxPercentAmount)
83 | {
84 | return 100 + (int)(100 * taxPercentAmount);
85 | }
86 |
87 | private int GetDirectorsTotalSalaryWithTax(decimal taxPercentAmount)
88 | {
89 | return 200 + (int) (200 * taxPercentAmount);
90 | }
91 |
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Delegate/DelegateClassTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.Delegate
8 | {
9 | public class DelegateClassTest
10 | {
11 | private readonly DelegateClass delegateObject = new DelegateClass();
12 |
13 | [Fact]
14 | public void ShouldReturnDirectorsSalary()
15 | {
16 | int directorsTotalSalary = delegateObject.GetTotalSalaryAmount(1);
17 |
18 | directorsTotalSalary.Should().Be(300);
19 | }
20 |
21 | [Fact]
22 | public void ShouldReturnConsultantsSalary()
23 | {
24 | int consultantsTotalSalary = delegateObject.GetTotalSalaryAmount(0);
25 |
26 | consultantsTotalSalary.Should().Be(200);
27 | }
28 |
29 | [Fact]
30 | public void ShouldReturnDirectorsSalaryUsingBuiltinDelegate()
31 | {
32 | int directorsTotalSalary = delegateObject.GetTotalSalaryAmountUsingFuncBuitinDelegate(2);
33 |
34 | directorsTotalSalary.Should().Be(300);
35 | }
36 |
37 | [Fact]
38 | public void ShouldReturnConsultantsSalaryUsingBuiltinDelegate()
39 | {
40 | int consultantsTotalSalary = delegateObject.GetTotalSalaryAmountUsingFuncBuitinDelegate(1);
41 |
42 | consultantsTotalSalary.Should().Be(200);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Delegate/MulticastDelegateClass.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Reflection;
4 | using System.Text;
5 |
6 | namespace TheCSharp.Delegate
7 | {
8 | public class MulticastDelegateClass
9 | {
10 | private delegate int CalculateEmployees();
11 | private List calculateEmployeeDelegates = new List();
12 | private readonly System.Delegate allDelegate;
13 |
14 | public MulticastDelegateClass()
15 | {
16 | calculateEmployeeDelegates.Add(CalculateFullTimeEmployees);
17 | calculateEmployeeDelegates.Add(CalculatePartTimeEmployees);
18 | allDelegate = MulticastDelegate.Combine(calculateEmployeeDelegates.ToArray());
19 | }
20 |
21 | public int CountTotalEmployees()
22 | {
23 | int totalEmployees = 0;
24 | foreach(System.Delegate calculate in allDelegate.GetInvocationList())
25 | {
26 | totalEmployees += (int) calculate.DynamicInvoke();
27 | }
28 |
29 | return totalEmployees;
30 | }
31 |
32 | private int CalculateFullTimeEmployees()
33 | {
34 | return 100;
35 | }
36 |
37 | private int CalculatePartTimeEmployees()
38 | {
39 | return 200;
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Delegate/MulticastDelegateClassTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.Delegate
8 | {
9 | public class MulticastDelegateClassTest
10 | {
11 | private readonly MulticastDelegateClass multicastDelegateObject = new MulticastDelegateClass();
12 |
13 | [Fact]
14 | public void ShouldReturnAllEmployeesCount()
15 | {
16 | int totalEmployeesCount = multicastDelegateObject.CountTotalEmployees();
17 |
18 | totalEmployeesCount.Should().Be(300);
19 | }
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Delegate/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ###########################################################################
2 |
3 | # Introduced from Version 1
4 |
5 | # Delegate are nothing but function representation (function pointer in c)
6 |
7 | # 2 types of delegate i) SingleCast ii) Multicast
8 |
9 | # Built in void return type delegte is Action and non void return type is Func
10 |
11 | # Allows method level runtime polymorphism
12 |
13 | # Allow function as first class citizen (function as argument, function as return type)
14 |
15 | ###########################################################################
16 |
--------------------------------------------------------------------------------
/Src/TheCSharp/DynamicType/DynamicType.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.Dynamic
6 | {
7 | public class DynamicType
8 | {
9 | public dynamic CreateDynamicEmployee(int id, string name, DateTime dateOfBirth)
10 | {
11 | var employee = new Employee
12 | {
13 | Id = id,
14 | Name = name
15 | };
16 |
17 | dynamic dynamicEmp = employee;
18 | dynamicEmp.DateOfBirth = dateOfBirth; //once it assigned can not be added diffent property
19 |
20 | return dynamicEmp;
21 | }
22 |
23 | public Employee Transform(dynamic employee)
24 | {
25 | var emp = new Employee
26 | {
27 | Id = employee.Id,
28 | Name = employee.Name,
29 | DateOfBirth = employee.DateOfBirth
30 | };
31 |
32 | return emp;
33 | }
34 |
35 | public Employee TransformV2(dynamic employee)
36 | {
37 | Employee emp = employee;
38 | // Employee emp2 = (Employee) employee; // no need to explicit type casting
39 | return emp;
40 | }
41 |
42 | public int GetSalary(dynamic employee)
43 | {
44 | int salary = employee.GetEmployeeSalary(10);
45 |
46 | return salary;
47 | }
48 |
49 | public int GetAge(int employeeId)
50 | {
51 | return employeeId / 4;
52 | }
53 |
54 | public int GetAge(dynamic employeeId)
55 | {
56 | return employeeId / 4;
57 | }
58 |
59 | public bool IsDynamicObjectEmployeeType(dynamic employee)
60 | {
61 | Type type = employee.GetType();
62 |
63 | return type.Name.Equals("Employee");
64 | }
65 |
66 | }
67 |
68 | public class Employee
69 | {
70 | public int Id { get; set; }
71 |
72 | public string Name { get; set; }
73 |
74 | public DateTime DateOfBirth { get; set; }
75 |
76 | public int GetEmployeeSalary(int taxAmount)
77 | {
78 | return 100 + taxAmount;
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/Src/TheCSharp/DynamicType/DynamicTypeTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.Dynamic
8 | {
9 | public class DynamicTypeTest
10 | {
11 | private readonly DynamicType dynamicType = new DynamicType();
12 |
13 | [Fact]
14 | public void ShouldCreateDynamicEmployeeWhenEmployeePropertiesProvided()
15 | {
16 | var dateOfBirth = new DateTime(1970, 5, 6);
17 |
18 | dynamic employee = dynamicType.CreateDynamicEmployee(1999, "Employee-1", dateOfBirth);
19 |
20 | int employeeId = employee.Id;
21 | DateTime employeeDateOfBirth = employee.DateOfBirth;
22 |
23 | employeeId.Should().Be(1999);
24 | employeeDateOfBirth.Should().Be(dateOfBirth);
25 | }
26 |
27 | [Fact]
28 | public void ShouldTransformEmployeeWhenDynamicEmployeeProvided()
29 | {
30 | var dateOfBirth = new DateTime(1970, 5, 6);
31 | dynamic dynamicEmployee = new Employee();
32 | dynamicEmployee.Id = 11;
33 | dynamicEmployee.Name = "Empoyee-11";
34 | dynamicEmployee.DateOfBirth = dateOfBirth;
35 |
36 | Employee employee = dynamicType.Transform(dynamicEmployee);
37 |
38 | employee.Id.Should().Be(11);
39 | employee.Name.Should().Be("Empoyee-11");
40 | employee.DateOfBirth.Should().Be(dateOfBirth);
41 | }
42 |
43 | [Fact]
44 | public void ShouldTransformEmployeeV2WhenDynamicEmployeeProvided()
45 | {
46 | var dateOfBirth = new DateTime(1970, 5, 6);
47 | dynamic dynamicEmployee = new Employee();
48 | dynamicEmployee.Id = 11;
49 | dynamicEmployee.Name = "Empoyee-11";
50 | dynamicEmployee.DateOfBirth = dateOfBirth;
51 |
52 | Employee employee = dynamicType.TransformV2(dynamicEmployee);
53 |
54 | employee.Id.Should().Be(11);
55 | employee.Name.Should().Be("Empoyee-11");
56 | employee.DateOfBirth.Should().Be(dateOfBirth);
57 | }
58 |
59 | [Fact]
60 | public void ShouldReturnSalaryWhenEmployeeDynamicObjectProvided()
61 | {
62 | dynamic employee = new Employee();
63 |
64 | int salary = dynamicType.GetSalary(employee);
65 |
66 | salary.Should().Be(110);
67 | }
68 |
69 | [Fact]
70 | public void PolymorphismTest()
71 | {
72 | int staticAge = 100;
73 | dynamic dynamicAge = staticAge;
74 |
75 | int staticReturnAge = dynamicType.GetAge(staticAge);
76 | int dynamicReturnAge = dynamicType.GetAge(dynamicAge);
77 |
78 | staticReturnAge.Should().Be(dynamicReturnAge);
79 | }
80 |
81 | [Fact]
82 | public void DynamicTypeCheck()
83 | {
84 | dynamic dynamicEmployee = new Employee { Id = 1 };
85 |
86 | bool employeeType = dynamicType.IsDynamicObjectEmployeeType(dynamicEmployee);
87 |
88 | employeeType.Should().BeTrue();
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/Src/TheCSharp/DynamicType/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ###########################################################################
2 |
3 | # dynamic is a type that can avoid compile time type checking
4 |
5 | # It resolve at runtime. So all exception is thrown at runtime.
6 |
7 | # Dynamic type variable is created using "dynamic" keyword.
8 |
9 | # Visual studio does not provide any intellesence.
10 |
11 | # It is different than "var"
12 |
13 | # It is introduce from c# version 4
14 |
15 | # It is diffenet from object type as well. Object type has boxing and unboxing. So it is slow. But dynamic is fast.
16 |
17 | # in dynamic, any incorrect casting can create runtime error.
18 |
19 | ###########################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/DynamicType/dynamictype.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/DynamicType/dynamictype.png
--------------------------------------------------------------------------------
/Src/TheCSharp/Events/EventClass.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Text;
5 |
6 | namespace TheCSharp.Events
7 | {
8 | public class EmployeeService
9 | {
10 | // declaring delegate and event
11 | public delegate void AccountLockedDelegate(string employeeId, string employeeName);
12 | public event AccountLockedDelegate AccountLockedEvent;
13 | private readonly AccountService accountService;
14 |
15 | public EmployeeService(AccountService accountService)
16 | {
17 | this.accountService = accountService;
18 | }
19 |
20 | public bool ResigneEmployee(string employeeId)
21 | {
22 | Debug.WriteLine($"Resign Employee={employeeId}");
23 |
24 | bool accountLocked = accountService.LockEmployeeAccount(employeeId);
25 |
26 | if (accountLocked && AccountLockedEvent != null)
27 | {
28 | AccountLockedEvent(employeeId, $"Mr.{employeeId}");
29 | }
30 |
31 | return true;
32 | }
33 | }
34 |
35 | ///
36 | /// Employee Account Service
37 | ///
38 | public class AccountService
39 | {
40 | ///
41 | /// Employee Account lock
42 | ///
43 | ///
44 | ///
45 | public bool LockEmployeeAccount(string employeeId)
46 | {
47 | Debug.WriteLine($"Locked Employee={employeeId}");
48 |
49 | return true;
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Events/EventClassTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.Text;
6 | using Xunit;
7 |
8 | namespace TheCSharp.Events
9 | {
10 | public class EventClassTest
11 | {
12 | private readonly EmployeeService employeeService;
13 | private readonly AccountService accountService;
14 |
15 | public EventClassTest()
16 | {
17 | accountService = new AccountService();
18 | employeeService = new EmployeeService(accountService);
19 |
20 | employeeService.AccountLockedEvent += delegate (string employeeId, string employeeName)
21 | {
22 | Debug.WriteLine($"Locked Employee Name={employeeName}");
23 | };
24 | }
25 |
26 | [Fact]
27 | public void LockEmployeeAccountWhenEmployeeResigned()
28 | {
29 | string employeeId = "E001";
30 |
31 | bool succeed = employeeService.ResigneEmployee(employeeId);
32 |
33 | succeed.Should().Be(true);
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Events/Events.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/Events/Events.JPG
--------------------------------------------------------------------------------
/Src/TheCSharp/Events/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ###########################################################################
2 |
3 | # A notification that inform other objects that something happened
4 |
5 | # Declare a delegate
6 |
7 | # Declare a variable with that delegate with event keyword
8 |
9 | # Raise the event when needed.
10 |
11 | # Events are synchonously processed.
12 |
13 | ###########################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/ExceptionHandling/Exception.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/ExceptionHandling/Exception.png
--------------------------------------------------------------------------------
/Src/TheCSharp/ExceptionHandling/ExceptionHander.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Text;
5 |
6 | namespace TheCSharp.ExceptionHandling
7 | {
8 | public class ExceptionHander
9 | {
10 | ///
11 | /// Throw a custom Exception when argument is less than 1
12 | ///
13 | ///
14 | [DebuggerStepThrough]
15 | public void ThrowACustomException(int value)
16 | {
17 | if (value < 1)
18 | throw new MyCustomException("Value should not be 0 or negative. Learning purpose only!");
19 | }
20 |
21 | ///
22 | /// Demonastare simple handling exception best practice
23 | ///
24 | ///
25 | public int HandleException()
26 | {
27 | // try-catch-finally -> finally is optional
28 | try
29 | {
30 | throw new MyCustomException("Learning purpose only!");
31 | }
32 | catch(MyCustomException ex)
33 | {
34 | Debug.WriteLine(ex.Message); // Good practice and it should be (specific exception handle),
35 | }
36 | catch(Exception ex) // base exception (Generale exception handling)
37 | {
38 | Debug.WriteLine(ex.Message);
39 | }
40 | finally
41 | {
42 | Debug.WriteLine("Finally block is executing...");
43 | }
44 |
45 | return 1;
46 | }
47 |
48 | ///
49 | /// Demonastrate Nesting Exception
50 | ///
51 | public void HandleNestedException()
52 | {
53 | int value = 0;
54 | int totalValue = 100;
55 | int result = 0;
56 |
57 | try
58 | {
59 | result = totalValue / value;
60 | }
61 | catch(DivideByZeroException e)
62 | {
63 | try
64 | {
65 | result = result / 0;
66 | }
67 | catch(DivideByZeroException ex)
68 | {
69 | Debug.Write("Message from inner exception");
70 | }
71 | }
72 | }
73 |
74 | public void HandleExceptionAndThenRethrow()
75 | {
76 | int firstValue = 100;
77 | int secondValue = 0;
78 |
79 | try
80 | {
81 | int result = firstValue / secondValue;
82 | }
83 | catch(DivideByZeroException ex)
84 | {
85 | // exception reported
86 | Debug.WriteLine("Sorry! first value should not be devided by zero. It is forbedden.");
87 |
88 | throw;
89 |
90 | /* 1:
91 | throw; // throwing
92 | */
93 |
94 | /* 2:
95 | * throwing and rethowing has difference. rethrowing change the stack trace of the original exception
96 | throw ex; // retrhowing
97 | */
98 |
99 | /* 3:
100 | * Another way. In this case the original exception will be in inner Exception
101 | throw new Exception("Sorry! Should not be allowed to devide by zero", ex);
102 | */
103 | }
104 | }
105 |
106 | ///
107 | /// Filtering exception based on logic
108 | ///
109 | public void FilterException()
110 | {
111 | int value = -1;
112 | try
113 | {
114 | throw new ArgumentNullException("The argument should not be null");
115 | }
116 | catch(Exception ex) when (WillExceptionHandled(value)) // only when WillExceptionHandled method return true then it will be handled
117 | {
118 | Debug.WriteLine(ex.Message);
119 | }
120 | }
121 |
122 | private bool WillExceptionHandled(int value)
123 | {
124 | return value <1 ? true : false;
125 | }
126 | }
127 |
128 |
129 | ///
130 | /// Creating a Custom Exception
131 | ///
132 | public class MyCustomException : ApplicationException
133 | {
134 | public MyCustomException()
135 | {
136 | }
137 | public MyCustomException(string message) : base(message)
138 | {
139 | }
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/Src/TheCSharp/ExceptionHandling/ExceptionHanderTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using Xunit;
5 |
6 | namespace TheCSharp.ExceptionHandling
7 | {
8 | public class ExceptionHanderTest
9 | {
10 | private readonly ExceptionHander exceptionHandler = new ExceptionHander();
11 |
12 | [Fact]
13 | public void ShouldThrowCustomException()
14 | {
15 | int value = -1;
16 | Assert.Throws(() =>
17 | exceptionHandler.ThrowACustomException(value)
18 | );
19 | }
20 |
21 | [Fact]
22 | public void ShouldCatchRethrowAnException()
23 | {
24 | try
25 | {
26 | exceptionHandler.HandleExceptionAndThenRethrow();
27 | }
28 | catch (DivideByZeroException ex)
29 | {
30 | }
31 | }
32 |
33 |
34 | [Fact]
35 | public void ShouldHandleException()
36 | {
37 | exceptionHandler.HandleException();
38 | }
39 |
40 | [Fact]
41 | public void ShouldHandleNestedException()
42 | {
43 | exceptionHandler.HandleNestedException();
44 | }
45 |
46 | [Fact]
47 | public void ShouldFilterException()
48 | {
49 | exceptionHandler.FilterException();
50 | }
51 |
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/Src/TheCSharp/ExceptionHandling/ReadMe.txt:
--------------------------------------------------------------------------------
1 | #################################################################################################################
2 |
3 | # Errors and Exceptions are not always same. Many times with simple validations error can be avoided.
4 |
5 | # Lots of things need to consider when you catch and throw any exception.
6 |
7 | # Try-Catch-Finally is the basic construct (Finally block is always executed whether exception is raised or not)
8 |
9 | # Exception filter comes from C# version 6.0 (Allow up to add condigion clause for each catch block)
10 |
11 | # Do not try to catch exception when you are not clear about the exception
12 |
13 | # If you throw any custom exception please give a detail message with that exception.
14 |
15 | # Throwing & Retrhowing exception has difference.
16 |
17 | # Exception handling and exception reporting/logging is very important for the health of the software.
18 |
19 | # Do not ignore any exception.
20 |
21 | #################################################################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/ExpressionTree/ExpressionTree.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Linq.Expressions;
5 |
6 | namespace TheCSharp.ExpressionTree
7 | {
8 | public class ExpressionTree
9 | {
10 | private Expression> lambdaExpresion;
11 |
12 | ///
13 | /// Add 2 variables using Expression Tree
14 | ///
15 | ///
16 | ///
17 | ///
18 | public int Add(int x, int y)
19 | {
20 | Expression> expressionTree = (num1, num2) => num1 + num2;
21 | Func func = expressionTree.Compile();
22 |
23 | return func(x, y);
24 | }
25 |
26 | ///
27 | /// Multiply 2 variables
28 | ///
29 | ///
30 | ///
31 | ///
32 | public int Multiply(int x, int y)
33 | {
34 | ConstantExpression left = Expression.Constant(x);
35 | ConstantExpression right = Expression.Constant(y);
36 |
37 | BinaryExpression binaryExpression = Expression.Multiply(left, right);
38 |
39 | Expression> lambdaExpresion = Expression.Lambda>(binaryExpression);
40 |
41 | int sum = lambdaExpresion.Compile()();
42 |
43 | return sum;
44 | }
45 |
46 | ///
47 | /// Calculate Factorial using Expression Tree => fact = n * (n-1) * (n-2) * .... 1
48 | ///
49 | ///
50 | ///
51 | public int GetFactorial(int intValue)
52 | {
53 | ParameterExpression valueExpression = Expression.Parameter(typeof(int), "value");
54 | ParameterExpression resultExpression = Expression.Parameter(typeof(int), "result");
55 | LabelTarget labelTarget = Expression.Label(typeof(int));
56 |
57 | BlockExpression blockExpression = Expression.Block(
58 | new[] { resultExpression },
59 | Expression.Assign(resultExpression, Expression.Constant(1)),
60 | Expression.Loop( // loop block
61 | Expression.IfThenElse(
62 | Expression.GreaterThan(valueExpression, Expression.Constant(1)),
63 | Expression.MultiplyAssign(resultExpression, Expression.PostDecrementAssign(valueExpression)), // multiplication operation
64 | Expression.Break(labelTarget, resultExpression)), // break condition
65 | labelTarget)
66 | );
67 |
68 | int factorial = Expression.Lambda>(blockExpression, valueExpression).Compile()(intValue); // executing code
69 |
70 | return factorial;
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/Src/TheCSharp/ExpressionTree/ExpressionTree.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/ExpressionTree/ExpressionTree.png
--------------------------------------------------------------------------------
/Src/TheCSharp/ExpressionTree/ExpressionTreeTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.ExpressionTree
8 | {
9 | public class ExpressionTreeTest
10 | {
11 | private readonly ExpressionTree expressionTree = new ExpressionTree();
12 |
13 | [Fact]
14 | public void ShouldAddWhenProvidTwoNumber()
15 | {
16 | int x = 20;
17 | int y = 10;
18 |
19 | int z = expressionTree.Add(x, y);
20 |
21 | z.Should().Be(30);
22 | }
23 |
24 | [Fact]
25 | public void ShouldMultiplyWhenProvidTwoNumberV2()
26 | {
27 | int x = 20;
28 | int y = 10;
29 |
30 | int z = expressionTree.Multiply(x, y);
31 |
32 | z.Should().Be(200);
33 | }
34 |
35 | [Fact]
36 | public void ShouldReturnFactorialWhenAnyIntegerProvided()
37 | {
38 | int value = 6;
39 |
40 | int factorial = expressionTree.GetFactorial(value);
41 |
42 | factorial.Should().Be(720);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Src/TheCSharp/ExpressionTree/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ################################################################################
2 |
3 | # Describe operation as data that can produce result.
4 |
5 | # We can use expression tree in 2 directions i) Via API then compile at runtime ii) from provided lambda expression
6 |
7 | # The scope of ExpressionTree is little big. You need to explore more...
8 |
9 | ################################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/ExtensionMethod/ExtensionMethod.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/ExtensionMethod/ExtensionMethod.png
--------------------------------------------------------------------------------
/Src/TheCSharp/ExtensionMethod/ExtenstionMethod.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.ExtensionMethod
6 | {
7 | public class EmployeeService
8 | {
9 | public int CalculatePayableSalary(string employeeId)
10 | {
11 | int taxAmount = 100;
12 | int totalSaalary = 1000;
13 |
14 | if (employeeId.Substring(0) == "A")
15 | {
16 | return totalSaalary - taxAmount;
17 | }
18 |
19 | return totalSaalary;
20 | }
21 |
22 |
23 | public int CalculateBonus(string employeeId)
24 | {
25 | int maxBonus = 1000;
26 |
27 | if (employeeId.Length == 3)
28 | {
29 | return maxBonus;
30 | }
31 |
32 | return maxBonus / 2;
33 | }
34 | }
35 |
36 |
37 | public static class EmployeeServiceExtension
38 | {
39 | public static int CalculateDevident(this EmployeeService employeeService, string employeeId, int totalDevident)
40 | {
41 | if (null == employeeId || totalDevident == 0)
42 | {
43 | return 0;
44 | }
45 |
46 | if (employeeId.Contains("A"))
47 | {
48 | return totalDevident;
49 | }
50 |
51 | if (employeeId.Contains("B"))
52 | {
53 | return totalDevident / 2;
54 | }
55 |
56 | return totalDevident / 4;
57 | }
58 | }
59 |
60 | public static class StringExtension
61 | {
62 | public static string FirstTwoCharacters(this string stringValue)
63 | {
64 | if (null == stringValue)
65 | {
66 | return string.Empty;
67 | }
68 |
69 | return stringValue.Substring(0, 2);
70 | }
71 | }
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/Src/TheCSharp/ExtensionMethod/ExtentionMethodTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.ExtensionMethod
8 | {
9 | public class ExtentionMethodTest
10 | {
11 | private readonly EmployeeService employeeService = new EmployeeService();
12 |
13 | [Fact]
14 | public void ShouldGetEmployeeDevident()
15 | {
16 | int employeeDevident1 = employeeService.CalculateDevident(null, 100);
17 | int employeeDevident2 = employeeService.CalculateDevident("A01", 0);
18 | int employeeDevident3 = employeeService.CalculateDevident("A01", 100);
19 | int employeeDevident4 = employeeService.CalculateDevident("B01", 100);
20 | int employeeDevident5 = employeeService.CalculateDevident("C01", 100);
21 |
22 | employeeDevident1.Should().Be(0);
23 | employeeDevident2.Should().Be(0);
24 | employeeDevident3.Should().Be(100);
25 | employeeDevident4.Should().Be(50);
26 | employeeDevident5.Should().Be(25);
27 | }
28 |
29 | [Fact]
30 | public void ShouldReturnFirstCharacterWhenValidStringProvided()
31 | {
32 | string countryName = "Bangladesh";
33 |
34 | string firstTwoCharacter = countryName.FirstTwoCharacters();
35 |
36 | firstTwoCharacter.Should().Be("Ba");
37 |
38 |
39 | // you cal call Extension method as static method as well
40 |
41 | string firstTwo = StringExtension.FirstTwoCharacters(countryName);
42 |
43 | firstTwo.Should().Be("Ba");
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Src/TheCSharp/ExtensionMethod/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ##############################################################################################################
2 |
3 | # Extension Method feature is introduced from C# version 3
4 |
5 | # Adding new method of existing type without inheritence/recompile and also not touching with original type.
6 |
7 | # Cannot possible to override any method using this.
8 |
9 | $ Its scope is namespace level.
10 |
11 | # Cannot extend static class using externsion method
12 |
13 | ##############################################################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/Generic/Generic.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.Generic
6 | {
7 | public abstract class Employee
8 | {
9 | public string Id { get; set; }
10 |
11 | public abstract int CalculateSalary();
12 | }
13 |
14 | public class FullTimeEmployee : Employee
15 | {
16 | public override int CalculateSalary()
17 | {
18 | return 200;
19 | }
20 | }
21 |
22 | public class PartTimeEmployee : Employee
23 | {
24 | public override int CalculateSalary()
25 | {
26 | return 100;
27 | }
28 | }
29 |
30 | ///
31 | /// Generic Employee Service
32 | ///
33 | ///
34 | public class EmployeeRepository where T : Employee
35 | {
36 | private IList employees = new List();
37 |
38 | public EmployeeRepository()
39 | {
40 | employees.Add(new FullTimeEmployee() { Id = "F001" });
41 | employees.Add(new FullTimeEmployee() { Id = "F002" });
42 | employees.Add(new PartTimeEmployee() { Id = "P001" });
43 | employees.Add(new PartTimeEmployee() { Id = "P002" });
44 | }
45 |
46 | public IEnumerable GetEmployees()
47 | {
48 | return employees;
49 | }
50 |
51 | public void AddNewEmployee(Employee employee)
52 | {
53 | employees.Add(employee);
54 | }
55 |
56 | ///
57 | /// Generic Method -> Generic as return type
58 | ///
59 | ///
60 | ///
61 | ///
62 | public T2 CreateFullTimeEmployeeById(string id) where T2 : FullTimeEmployee
63 | {
64 | return (T2) new FullTimeEmployee { Id = id };
65 | }
66 |
67 | ///
68 | /// Generic type as arguments
69 | ///
70 | ///
71 | ///
72 | ///
73 | ///
74 | public int CalculateSalary(T2 employee1, T2 employee2) where T2 : PartTimeEmployee
75 | {
76 | int totalSalary = employee1.CalculateSalary() + employee2.CalculateSalary();
77 |
78 | return totalSalary;
79 | }
80 | }
81 |
82 |
83 | public abstract class Animal
84 | {
85 | public string Name { get; set; }
86 | }
87 |
88 | public abstract class Bird : Animal
89 | {
90 | }
91 |
92 | public abstract class Domistic : Animal
93 | {
94 | }
95 |
96 | public class Parot : Bird
97 | {
98 | }
99 | public class Cat : Domistic
100 | {
101 | }
102 |
103 | ///
104 | /// Value type does not support variantused as Return type.
105 | ///
106 | ///
107 | public interface IAnimalReturnService
108 | {
109 | Animal GetAnimal();
110 | }
111 |
112 | ///
113 | /// Use only argument type
114 | ///
115 | ///
116 | public interface IAnimalAcceptService
117 | {
118 | void AcceptAnimal(Animal animal);
119 | }
120 |
121 | ///
122 | /// Capable of both Arguent and Return type
123 | ///
124 | ///
125 | public interface IAnimalAcceptReturnService
126 | {
127 | Animal AcceptAndReturn(Animal animal);
128 | }
129 |
130 |
131 | public class DefaultAnimalReturnService : IAnimalReturnService
132 | {
133 | public Animal GetAnimal()
134 | {
135 | return new Cat { Name = "Cat-100" };
136 | }
137 | }
138 |
139 | public class DefaultAnimalAcceptService : IAnimalAcceptService
140 | {
141 | private readonly IList animals = new List();
142 |
143 | public void AcceptAnimal(Animal animal)
144 | {
145 | animals.Add(animal);
146 | }
147 | }
148 |
149 | public class DefaultAnimalAcceptReturnService : IAnimalAcceptReturnService
150 | {
151 | public Animal AcceptAndReturn(Animal animal)
152 | {
153 | return animal;
154 | }
155 | }
156 |
157 | }
158 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Generic/GenericTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.Generic
8 | {
9 | public class GenericTest
10 | {
11 | private readonly EmployeeRepository employeeRepository = new EmployeeRepository();
12 |
13 | [Fact]
14 | public void ShouldReturnAllEmployees()
15 | {
16 | IEnumerable employees = employeeRepository.GetEmployees();
17 |
18 | employees.Should().HaveCount(4);
19 | }
20 |
21 | [Fact]
22 | public void ShouldAddANewEmployee()
23 | {
24 | var fullTimeEmployee = new FullTimeEmployee { Id = "F003" };
25 |
26 | employeeRepository.AddNewEmployee(fullTimeEmployee);
27 | }
28 |
29 | [Fact]
30 | public void ShouldCreateAFulLTimeEmployeeWhenIdisProvided()
31 | {
32 | const string employeeId = "F005";
33 |
34 | Employee employee = employeeRepository.CreateFullTimeEmployeeById(employeeId);
35 |
36 | employee.Id.Should().Be(employeeId);
37 | }
38 | }
39 |
40 | public class CoContraVarienceTest
41 | {
42 | private readonly IAnimalAcceptService animalAcceptService = new DefaultAnimalAcceptService();
43 | private readonly IAnimalReturnService animalReturnService = new DefaultAnimalReturnService();
44 | private readonly IAnimalAcceptReturnService animalAcceptReturnService = new DefaultAnimalAcceptReturnService();
45 |
46 | [Fact]
47 | public void ShouldAcceptAnyAnimal()
48 | {
49 | var parot = new Parot { Name = "MyParot-1" };
50 |
51 | animalAcceptService.AcceptAnimal(parot);
52 | }
53 |
54 | [Fact]
55 | public void ShouldReturnAnyAnimal()
56 | {
57 | var cat = (Cat)animalReturnService.GetAnimal();
58 |
59 | cat.Should().NotBeNull();
60 | }
61 |
62 | [Fact]
63 | public void ShouldAcceptAndReturnAnyAnimal()
64 | {
65 | var cat = new Cat { Name = "MyCat-1" };
66 |
67 | Cat returnCat = (Cat)animalAcceptReturnService.AcceptAndReturn(cat);
68 |
69 | returnCat.Should().NotBeNull();
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Generic/Generics.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/Generic/Generics.png
--------------------------------------------------------------------------------
/Src/TheCSharp/Generic/ReadMe.txt:
--------------------------------------------------------------------------------
1 | #####################################################################################################
2 |
3 | # Introduce from Version 2
4 |
5 | # Is is Type paramter as any class
6 |
7 | # Type level poliphorphisom feature.
8 |
9 | # Co,Contra, In Varience refere more/less derived/specific type use.
10 |
11 | # Co Variance allow us to use more derived type that declared as type parameter.
12 |
13 | # Contra Variance allow us to use less derived type that declared as type parameter.
14 |
15 | # Invariance allow us to use only that type declared. Default is Invariance
16 |
17 | #####################################################################################################
18 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Indexer/Indexer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Linq;
5 |
6 | namespace TheCSharp.Indexer
7 | {
8 | public class Indexer
9 | {
10 | private readonly string[] countries = new string[] { "Bangladesh", "India", "Pakistan" };
11 |
12 | ///
13 | /// Retrive and set country name from/to countries list using index
14 | ///
15 | ///
16 | ///
17 | public string this[int index]
18 | {
19 | get
20 | {
21 | string country = countries[index];
22 |
23 | return country;
24 | }
25 |
26 | set
27 | {
28 | countries[index] = value;
29 | }
30 | }
31 |
32 | ///
33 | /// Retrun index from countries using country name
34 | ///
35 | ///
36 | ///
37 | public int this[string countryName]
38 | {
39 | get
40 | {
41 | for(int index =0; index < countries.Length; index++)
42 | {
43 | if (countries[index].Equals(countryName) )
44 | {
45 | return index;
46 | }
47 | }
48 |
49 | return -1;
50 | }
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Indexer/Indexer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/Indexer/Indexer.png
--------------------------------------------------------------------------------
/Src/TheCSharp/Indexer/IndexerTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.Indexer
8 | {
9 | public class IndexerTest
10 | {
11 | private readonly Indexer indexer = new Indexer();
12 |
13 | [Fact]
14 | public void ShouldGetItemFromObjectWhenValidIndexProvided()
15 | {
16 | string country = indexer[0];
17 |
18 | country.Should().Be("Bangladesh");
19 | }
20 |
21 | [Fact]
22 | public void ShouldAddNewCountry()
23 | {
24 | string country = "USA";
25 | indexer[0] = country;
26 |
27 | string returnCountry = indexer[0];
28 |
29 | country.Should().Be("USA");
30 | }
31 |
32 | [Fact]
33 | public void ShouldReturnIndexWhenValidCountryNameProvided()
34 | {
35 | int index = indexer["India"];
36 |
37 | index.Should().Be(1);
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Indexer/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ############################################################################################
2 |
3 | # Allow an object to be indexed just like an array.
4 |
5 | # Very Similar to property
6 |
7 | # Indexer can be overloaded
8 |
9 | # Some people called it smart array
10 |
11 | ############################################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/LambdaExpression/LambdaExpression.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Linq;
5 |
6 | namespace TheCSharp.LambdaExpression
7 | {
8 | public class LambdaExpression
9 | {
10 | private readonly IList students = new List();
11 |
12 | public LambdaExpression()
13 | {
14 | students.Add(new Student { Id = 1, Name = "Student-1", Language = "Bangla" });
15 | students.Add(new Student { Id = 2, Name = "Student-2", Language = "English" });
16 | students.Add(new Student { Id = 3, Name = "Student-3", Language = "Bangla" });
17 |
18 | }
19 |
20 | public IEnumerable ExpressionLambda()
21 | {
22 | // Select is builtin lambda function
23 | IEnumerable studentDtoList = students.Select(item => new StudentDto { StudentId = item.Id, StudentName = item.Name });
24 |
25 | return studentDtoList;
26 | }
27 |
28 | public IEnumerable GetBanglaStudents()
29 | {
30 | // SelectCustom is newly created by me lambda function
31 | IEnumerable studentDtoList = students.SelectCustom(item => new StudentDto { StudentId = item.Id, StudentName = item.Name });
32 |
33 | return studentDtoList;
34 | }
35 |
36 |
37 | }
38 |
39 | public class Student
40 | {
41 | public long Id { get; set; }
42 |
43 | public string Name { get; set; }
44 |
45 | public string Language { get; set; }
46 | }
47 |
48 | public class StudentDto
49 | {
50 | public long StudentId { get; set; }
51 |
52 | public string StudentName { get; set; }
53 | }
54 |
55 | public static class LambdaExtension
56 | {
57 | public static IEnumerable SelectCustom(this IEnumerable students, Func func)
58 | {
59 | var list = new List();
60 |
61 | foreach (Student student in students)
62 | {
63 | if (student.Language.Equals("Bangla"))
64 | {
65 | StudentDto studentDto = func(student);
66 | list.Add(studentDto);
67 | }
68 | }
69 |
70 | return list;
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/Src/TheCSharp/LambdaExpression/LambdaExpression.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/LambdaExpression/LambdaExpression.png
--------------------------------------------------------------------------------
/Src/TheCSharp/LambdaExpression/LambdaExpressionTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.LambdaExpression
8 | {
9 | public class LambdaExpressionTest
10 | {
11 | private readonly LambdaExpression lambdaExpression = new LambdaExpression();
12 |
13 | [Fact]
14 | public void ShouldReturnAllStudents()
15 | {
16 | IEnumerable studentList = lambdaExpression.ExpressionLambda();
17 |
18 | studentList.Should().HaveCount(3);
19 | }
20 |
21 |
22 | [Fact]
23 | public void ShouldReturnBanglaStudents()
24 | {
25 | IEnumerable studentList = lambdaExpression.GetBanglaStudents();
26 |
27 | studentList.Should().HaveCount(2);
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Src/TheCSharp/LambdaExpression/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ####################################################################################
2 |
3 | # It is introduced C# version 3.0
4 |
5 | # Similar to anonymous function
6 |
7 | # => is lambda operator
8 |
9 | # 2 types of lambda i) Expression lambda [input => expression]
10 | ii) Statement lambda [input => {}]
11 |
12 |
13 |
14 | ####################################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/Linq/Linq.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Linq;
5 |
6 | namespace TheCSharp.Linq
7 | {
8 |
9 | public abstract class EntityBase
10 | {
11 | public string Id { get; set; }
12 |
13 | public string Name { get; set; }
14 | }
15 |
16 | public class Employee : EntityBase
17 | {
18 | public string Manager { get; set; }
19 |
20 | public string DepartmentId { get; set; }
21 | }
22 |
23 | public class Department : EntityBase
24 | {
25 | public string DepartmentHead { get; set; }
26 | }
27 |
28 | public class EmployeeDepartmentDto
29 | {
30 | public string EmployeeName { get; set; }
31 |
32 | public string DepartmentName { get; set; }
33 | }
34 |
35 | public class DepartmentEmployeeCountDto
36 | {
37 | public string DepartmentName { get; set; }
38 |
39 | public int NoofEmployees { get; set; }
40 | }
41 |
42 | public class EntityRepository
43 | {
44 | private readonly IList employees = new List();
45 | private readonly IList departments = new List();
46 |
47 | public EntityRepository()
48 | {
49 | departments.Add(new Department { Id = "IT", Name = "IT", DepartmentHead = "MR. IT" });
50 | departments.Add(new Department { Id = "Finance", Name= "Finance", DepartmentHead = "MR. Finance" });
51 |
52 | employees.Add(new Employee { Id = "E001", Name = "Employee-E001", Manager = "Manager-3", DepartmentId = "IT" });
53 | employees.Add(new Employee { Id = "E002", Name = "Employee-E002", Manager = "Manager-1", DepartmentId = "IT" });
54 | employees.Add(new Employee { Id = "E003", Name = "Employee-E003", Manager = "Manager-1", DepartmentId = "Finance" });
55 | employees.Add(new Employee { Id = "E004", Name = "Employee-E004", Manager = "Manager-2", DepartmentId = null });
56 | employees.Add(new Employee { Id = "E005", Name = "Employee-E005", Manager = "Manager-2", DepartmentId = null });
57 | }
58 |
59 | ///
60 | /// Demonastrate Inner join
61 | ///
62 | ///
63 | public IEnumerable FindEmployeesWhoHasDepartment()
64 | {
65 | IEnumerable employeeDtoList = employees.Join( //outer sequence
66 | departments, // inner sequence
67 | emp => emp.DepartmentId, // outer key
68 | dept => ((Department)dept).Id, // inner key
69 | (emp, dept) => new EmployeeDepartmentDto
70 | {
71 | EmployeeName = emp.Name,
72 | DepartmentName = dept.Name
73 | });
74 |
75 | return employeeDtoList;
76 | }
77 |
78 | ///
79 | /// Count no of employees per department using Groupby operator
80 | ///
81 | ///
82 | public IEnumerable CountDepartmentEmployees()
83 | {
84 | IEnumerable employeeDepartmentDtos = employees.Join(departments, emp => emp.DepartmentId,
85 | dept => ((Department)dept).Id, (emp, dept) => new EmployeeDepartmentDto
86 | {
87 | DepartmentName = dept.Name,
88 | EmployeeName = emp.Name
89 | }).ToList();
90 |
91 | // First grouping then counting and finally sorting by department name
92 | IEnumerable departwiseEmployeeCount = employeeDepartmentDtos.GroupBy(item => item.DepartmentName).Select(
93 | g => new DepartmentEmployeeCountDto { DepartmentName = g.First().DepartmentName, NoofEmployees = g.Count() })
94 | .OrderBy(item => item.DepartmentName); // order by departmentname
95 |
96 | return departwiseEmployeeCount;
97 | }
98 |
99 | public IEnumerable FindEmployeesWhoHasNoDepartment()
100 | {
101 | return employees.Where(employee => employee.DepartmentId == null).OrderByDescending(item => item.Name);
102 | }
103 |
104 | ///
105 | /// Filter clause from client side as form of Func delegate
106 | ///
107 | ///
108 | ///
109 | public IEnumerable FilterEmployees(Func func)
110 | {
111 | return employees.Where(func);
112 | }
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Linq/Linq.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/Linq/Linq.png
--------------------------------------------------------------------------------
/Src/TheCSharp/Linq/LinqTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using Xunit;
7 |
8 | namespace TheCSharp.Linq
9 | {
10 | public class LinqTest
11 | {
12 | private readonly EntityRepository entityRepository = new EntityRepository();
13 |
14 | [Fact]
15 | public void ShouldReturnEmployeesWhoHasDepartment()
16 | {
17 | IEnumerable employees = entityRepository.FindEmployeesWhoHasDepartment();
18 |
19 | employees.Should().HaveCount(3);
20 | employees.Any(item => item.EmployeeName.Equals("Employee-E001")).Should().BeTrue();
21 | }
22 |
23 | [Fact]
24 | public void ShouldReturnDepartwiseEmployeeCount()
25 | {
26 | IEnumerable departmentEmployeeCountDtos = entityRepository.CountDepartmentEmployees();
27 |
28 | departmentEmployeeCountDtos.First(item => item.DepartmentName == "IT").NoofEmployees.Should().Be(2);
29 | departmentEmployeeCountDtos.First(item => item.DepartmentName == "Finance").NoofEmployees.Should().Be(1);
30 | }
31 |
32 | [Fact]
33 | public void ShouldReturnEmployeeWhoHasNoDepartment()
34 | {
35 | IEnumerable employeeDepartments = entityRepository.FindEmployeesWhoHasDepartment();
36 |
37 | employeeDepartments.Should().HaveCount(2);
38 | }
39 |
40 | [Fact]
41 | public void ShouldFilterEmployees()
42 | {
43 | IEnumerable employees = entityRepository.FilterEmployees(item => item.DepartmentId == "IT");
44 | IEnumerable employees2 = entityRepository.FilterEmployees(item => item.DepartmentId == "IT" && item.Manager == "Manager-3");
45 |
46 | employees.Should().HaveCount(2);
47 | employees2.Should().HaveCount(1);
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Linq/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ########################################################################################
2 |
3 | # Introduced from .NET 3.5 C# 3.0
4 |
5 | # Main task is generate queries to retrive data from the data source (Linq compatable data source).
6 |
7 | # Provide common syntax for quering all datasources.
8 |
9 | # Linq takes deffered execution.
10 |
11 | # Many types of LINQ - Linq to objects, Linq to Xml, Linq to EntityFramework,
12 | Linq to Dataset, Linq to Sql (DLinq)
13 |
14 | # Many query operators - Select, From, Where, Orderby, Join, Groupby etc for supporing
15 | filtering, sorting, ordering grouping
16 |
17 | # Provide full type checking at compile time.
18 |
19 | # Linq supports query expression, Implicitly typed variables, Object and collection initializers,
20 | Anonymous types, Extension methods, and Lambda expressions.
21 |
22 | # Linq query can be reused and it increase code readability.
23 |
24 | # Linq consist with 3 layers, top layer is language extension then .NET framework components and then datasource.
25 |
26 | # All Linq components are under System.Linq namespace
27 |
28 | ########################################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/Nullable/Nullable.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/Nullable/Nullable.png
--------------------------------------------------------------------------------
/Src/TheCSharp/Nullable/NullableClass.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.Nullable
6 | {
7 | public class NullableClass
8 | {
9 | // Nullable = int?
10 | private int? age = null; // assign null
11 |
12 | public int GetAge()
13 | {
14 | int newAge = age ?? -1; // retrive value from nullable type
15 |
16 | return newAge;
17 | }
18 |
19 | public int? SetAge(int? age)
20 | {
21 | this.age = age;
22 |
23 | return this.age;
24 | }
25 |
26 | public bool IsAgeGreaterThan50(int? age)
27 | {
28 | if (age.HasValue && age.Value > 50) // checking nullable type
29 | {
30 | return true;
31 | }
32 |
33 | return false;
34 | }
35 |
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Nullable/NullableClassTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.Nullable
8 | {
9 | public class NullableClassTest
10 | {
11 | private readonly NullableClass nullableObject = new NullableClass();
12 |
13 | [Fact]
14 | public void ShouldGetAge()
15 | {
16 | int age = nullableObject.GetAge();
17 |
18 | age.Should().Be(-1);
19 | }
20 |
21 | [Fact]
22 | public void ShouldSetAge()
23 | {
24 | int? age = nullableObject.SetAge(50);
25 |
26 | age.Value.Should().Be(50);
27 | }
28 |
29 | [Fact]
30 | public void SholdReturnTrueWhenGraterThan50AgeProvided()
31 | {
32 | bool greaterThenFifty = nullableObject.IsAgeGreaterThan50(51);
33 |
34 | greaterThenFifty.Should().BeTrue();
35 | }
36 |
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Nullable/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ################################################################################
2 |
3 | # Introduced from C# Version 2.0
4 |
5 | # Value types does not support to store null. This problem is solved by this feature (Only for value types).
6 |
7 | # Main type os Nullable where T: sturct
8 |
9 | # Shorthand is ? (Nullable operator)
10 |
11 | # We can use ?? to store nullable type to non nullable type.
12 |
13 | ################################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/OperatorOverloading/OperatorOverloading.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.OperatorOverloading
6 | {
7 | public class Budget
8 | {
9 | public long Amount { get; private set; }
10 |
11 | public Budget()
12 | {
13 | }
14 |
15 | public Budget(long amount)
16 | {
17 | this.Amount = amount;
18 | }
19 |
20 | public static Budget operator +(Budget budge1, Budget budge2)
21 | {
22 | var budget = new Budget
23 | {
24 | Amount = budge1.Amount + budge2.Amount
25 | };
26 |
27 | return budget;
28 | }
29 |
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Src/TheCSharp/OperatorOverloading/OperatorOverloading.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/OperatorOverloading/OperatorOverloading.png
--------------------------------------------------------------------------------
/Src/TheCSharp/OperatorOverloading/OperatorOverloadingTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.OperatorOverloading
8 | {
9 | public class OperatorOverloadingTest
10 | {
11 | [Fact]
12 | public void ShouldSumBudge()
13 | {
14 | var budget1 = new Budget(100);
15 | var budget2 = new Budget(200);
16 |
17 | Budget budget3 = budget1 + budget2;
18 |
19 | budget3.Amount.Should().Be(300);
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Src/TheCSharp/OperatorOverloading/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ##########################################################################################
2 |
3 | # A user-defined type can overload a predefined C# operator
4 |
5 | # "operator" keyword for declaring custom operator
6 |
7 | # Public and Static modifier can be used
8 |
9 | # Opertor overloading has some guidelines. Please check:
10 | https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/operator-overloads
11 |
12 | ##########################################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/Parallel/Parallel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/Parallel/Parallel.png
--------------------------------------------------------------------------------
/Src/TheCSharp/Parallel/ParallelClass.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Linq;
5 | using System.Threading.Tasks;
6 | using System.Diagnostics;
7 |
8 | namespace TheCSharp.Parallel1
9 | {
10 |
11 | public class Data
12 | {
13 | public int Id { get; set; }
14 |
15 | public int Value { get; set; }
16 | }
17 |
18 |
19 | public class ParallelClass
20 | {
21 | ///
22 | /// Process data list using parallel programming -> using foreach loop
23 | ///
24 | ///
25 | public void ProcessData(IEnumerable data)
26 | {
27 | var options = new ParallelOptions()
28 | {
29 | MaxDegreeOfParallelism = 2
30 | };
31 |
32 | Parallel.ForEach(data, options, item =>
33 | {
34 | Debug.WriteLine($"{item.Id}- {item.Value}");
35 | });
36 | }
37 |
38 | ///
39 | /// Process data list using parallel programming -> using for loop
40 | ///
41 | ///
42 |
43 | public void ProcessData(Data[] data)
44 | {
45 | var options = new ParallelOptions()
46 | {
47 | MaxDegreeOfParallelism = 2
48 | };
49 |
50 | Parallel.For(0, data.Length - 1, options, i =>
51 | {
52 | Data local = data[i];
53 |
54 | Debug.WriteLine($"{local.Id}- {local.Value}");
55 | });
56 | }
57 |
58 | ///
59 | /// Process data list using parallel programming -> using ParallelQuery
60 | ///
61 | ///
62 | public void ProcessDataUsingParallelQuery(IEnumerable data)
63 | {
64 | var options = new ParallelOptions()
65 | {
66 | MaxDegreeOfParallelism = 2
67 | };
68 |
69 | data.AsParallel().ForAll(item =>
70 | {
71 | Debug.WriteLine(item.Value);
72 | });
73 | }
74 |
75 | ///
76 | /// Execute list of methods parallelly - using Invoke()
77 | ///
78 | ///
79 | public void Process(Action method1, Action method2)
80 | {
81 | var options = new ParallelOptions
82 | {
83 | MaxDegreeOfParallelism = 3
84 | };
85 |
86 | Parallel.Invoke(options, method1, method2);
87 | }
88 |
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Parallel/ParallelClassTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.Parallel1
8 | {
9 | public class ParallelClassTest
10 | {
11 | private readonly ParallelClass parallelObject = new ParallelClass();
12 |
13 | [Fact]
14 | public void ShouldProcessWhenDataProvided()
15 | {
16 | var dataList = new List { new Data { Id = 1, Value = 100 }, new Data { Id = 2, Value = 200 }, new Data { Id = 3, Value = 300 }, };
17 | Data[] dataArray = dataList.ToArray();
18 |
19 | parallelObject.ProcessData(dataList);
20 | parallelObject.ProcessData(dataArray);
21 | }
22 |
23 | [Fact]
24 | public void ShouldProcessWhenDataProvidedUsingParallelQuery()
25 | {
26 | var dataList = new List { new Data { Id = 1, Value = 100 }, new Data { Id = 2, Value = 200 }, new Data { Id = 3, Value = 300 }, };
27 |
28 | parallelObject.ProcessDataUsingParallelQuery(dataList);
29 | }
30 |
31 | [Fact]
32 | public void SholdProcesWhenMethodListProvided()
33 | {
34 | var method1 = new Action(() => { Console.WriteLine("Hello World!"); } );
35 |
36 | var method2 = new Action(() =>
37 | {
38 | for (int i = 0; i < 5; i++)
39 | {
40 | Debug.WriteLine($"Hello Wold {i}!");
41 | }
42 | });
43 |
44 | parallelObject.Process(method1, method2);
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Parallel/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 |
3 | # It introduce from C# version
4 |
5 | # Modern servers are multicore processors. Parallel programming codes to use multicore
6 | when processing.
7 |
8 | # It is a technique the execution flow is broken up into pieces at the same time to
9 | execute multi core environment for better performace.
10 |
11 | ###############################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/Partial/Partial.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/Src/TheCSharp/Partial/Partial.png
--------------------------------------------------------------------------------
/Src/TheCSharp/Partial/PartialClassTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.Partial
8 | {
9 | public class PartialClassTest
10 | {
11 | private readonly PurchaseService purchaseService = new PurchaseService();
12 |
13 | [Fact]
14 | public void ShouldReturnTodaysPurchaseAmount()
15 | {
16 | int todaysPurchase = purchaseService.GetTodyasPurchaseAmount();
17 |
18 | todaysPurchase.Should().Be(10000);
19 | }
20 |
21 | [Fact]
22 | public void ShouldReturnYesterdaysPurchaseAmount()
23 | {
24 | int yesterdaysPurchase = purchaseService.GetYesterdaysPurchaseAmount();
25 |
26 | yesterdaysPurchase.Should().Be(20000);
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Partial/PartialFile1.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.Partial
6 | {
7 | public partial class PurchaseService
8 | {
9 | public int GetTodyasPurchaseAmount()
10 | {
11 | return 10000;
12 | }
13 |
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Partial/PartialFile2.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.Partial
6 | {
7 | public partial class PurchaseService
8 | {
9 | public int GetYesterdaysPurchaseAmount()
10 | {
11 | return 20000;
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Partial/PartialMethod1.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.Partial
6 | {
7 | public partial class UserService
8 | {
9 | partial void TrackUser(string userId);
10 |
11 | public bool IsUserValid(string userId)
12 | {
13 | TrackUser(userId);
14 | Guid userGuid;
15 | bool okay = Guid.TryParse(userId, out userGuid);
16 |
17 | return okay;
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Partial/PartialMethod2.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Text;
5 |
6 | namespace TheCSharp.Partial
7 | {
8 | public partial class UserService
9 | {
10 | partial void TrackUser(string userId)
11 | {
12 | Debug.WriteLine($"Tracked user id={userId}");
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Partial/PartialMethodTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.Partial
8 | {
9 | public class PartialMethodTest
10 | {
11 | private readonly UserService userService = new UserService();
12 |
13 | [Fact]
14 | public void ShouldTrackUserWhenValidUserIdProvided()
15 | {
16 | bool valid = userService.IsUserValid(Guid.NewGuid().ToString());
17 |
18 | valid.Should().BeTrue();
19 | }
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Src/TheCSharp/Partial/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ###########################################################################
2 |
3 | # Main reason is One class should share with multiple files
4 |
5 | # 2 types of partial
6 | 1) Partial Class
7 | 2) Partial Method
8 |
9 | # Very carefully create partical classes. Sometimes it creates navigational/reading problem. For example
10 | if any partial class implement any interface it extra efforts are needed to organize interface implementation.
11 |
12 | # Personally I am not verymuch fan of Partial feature.
13 |
14 | # Partial method must be return void
15 |
16 | # Partial method shold not be contain acces modifier
17 |
18 | # Partial method first declare then write its implementation (previous c/c++ function/method)
19 |
20 | ###########################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/PatternMatching/PatternMatching.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TheCSharp.PatternMatching
6 | {
7 | public class StudentBase
8 | {
9 | public long Id { get; set; }
10 |
11 | public string Name { get; set; }
12 | }
13 |
14 | public class FullTimeStudent : StudentBase
15 | {
16 | }
17 |
18 | public class PartTimeStudent : StudentBase
19 | {
20 | public int Age { get; set; }
21 | }
22 |
23 | public class PatternMatching
24 | {
25 |
26 | ///
27 | /// Pattern matching by is operator
28 | ///
29 | ///
30 | ///
31 | public bool IsFullTimeStudent(StudentBase student)
32 | {
33 | return student is FullTimeStudent;
34 | }
35 |
36 |
37 | ///
38 | /// Return countryname from country code using pattern matching
39 | ///
40 | ///
41 | ///
42 | public string FindCountryName(string countryCode)
43 | {
44 | string countryName = countryCode switch
45 | {
46 | "bd" => "Bangladesh",
47 | "in" => "India",
48 | "pak" => "Pakistan",
49 | _ => string.Empty
50 | };
51 |
52 | return countryName;
53 | }
54 |
55 |
56 | public int CalculateBonusPoint(StudentBase student)
57 | {
58 | int bonusPoint = student switch
59 | {
60 | StudentBase std when std is FullTimeStudent => 200,
61 | StudentBase std when std is PartTimeStudent => 100,
62 | _ => 0
63 | };
64 |
65 | return bonusPoint;
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Src/TheCSharp/PatternMatching/PatternMatchingTest.cs:
--------------------------------------------------------------------------------
1 | using FluentAssertions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace TheCSharp.PatternMatching
8 | {
9 | public class PatternMatchingTest
10 | {
11 | private readonly PatternMatching patternMatching = new PatternMatching();
12 |
13 | [Fact]
14 | public void ShouldCheckSpecificType()
15 | {
16 | StudentBase student = new FullTimeStudent { Id = 1, Name = "FullTimeStudent-1" };
17 |
18 | bool yes = patternMatching.IsFullTimeStudent(student);
19 |
20 | yes.Should().BeTrue();
21 | }
22 |
23 | [Fact]
24 | public void ShouldRetrunCountryNameWhenCountryCodeProvided()
25 | {
26 | string countryCode = "bd";
27 |
28 | string countryName = patternMatching.FindCountryName(countryCode);
29 |
30 | countryName.Should().Be("Bangladesh");
31 | }
32 |
33 | [Fact]
34 | public void ShouldCalculateBonusPoint()
35 | {
36 | StudentBase fullTimeStudent = new FullTimeStudent { Id = 1 };
37 | StudentBase partTimeStudent = new PartTimeStudent { Id = 100 };
38 |
39 | int bonusPointForFullTimeStudent = patternMatching.CalculateBonusPoint(fullTimeStudent);
40 | int bonusPointForPartTimeStudent = patternMatching.CalculateBonusPoint(partTimeStudent);
41 |
42 | bonusPointForFullTimeStudent.Should().Be(200);
43 | bonusPointForPartTimeStudent.Should().Be(100);
44 | }
45 |
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Src/TheCSharp/PatternMatching/ReadMe.txt:
--------------------------------------------------------------------------------
1 | ###########################################################################################
2 |
3 | # Introduce from C# Version 7.0
4 |
5 | # Pattern matching can extract value from expression
6 |
7 | # 2 cases we can use i) expression ii) switch statement
8 |
9 | ###########################################################################################
--------------------------------------------------------------------------------
/Src/TheCSharp/TheCSharp.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/docs/dt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/docs/dt.png
--------------------------------------------------------------------------------
/docs/f1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/docs/f1.png
--------------------------------------------------------------------------------
/docs/f2.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/docs/f2.JPG
--------------------------------------------------------------------------------
/docs/fu.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/docs/fu.jpg
--------------------------------------------------------------------------------
/docs/his.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/docs/his.png
--------------------------------------------------------------------------------
/docs/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/docs/logo.png
--------------------------------------------------------------------------------
/docs/others.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/habibsql/TheCSharp/b2ed2e98f0c194b6f11c4d741a2fdbd922bb9c5d/docs/others.gif
--------------------------------------------------------------------------------