├── .gitattributes ├── .gitignore ├── CSharp Code Samples ├── CSharp Code Samples.sln └── CodeSamples │ ├── Alterations │ ├── EntityConversionSample.cs │ ├── Extensions │ │ ├── ClassExtensionSample.cs │ │ └── ClassExtensions.cs │ └── OperatorOverloadingSample.cs │ ├── App.config │ ├── Attributes │ ├── ConditionalSample.cs │ ├── CustomAttributesSample.cs │ ├── DebuggingSample.cs │ └── ObsoleteSample.cs │ ├── Classes │ ├── AccessModifiersSample.cs │ ├── AnonymousTypesSample.cs │ ├── CallerInfoSample.cs │ ├── ClassAndMethodNamesSample.cs │ ├── ConstructorChainingSample.cs │ ├── GenericsSample.cs │ └── StaticSample.cs │ ├── ClipboardUse │ └── ClipboardSample.cs │ ├── CodeSamples.csproj │ ├── Comparing │ ├── CompareSample.cs │ ├── EqualityComparer.cs │ └── Equatable.cs │ ├── ConditionalDefines │ └── ConditionalDefinesSample.cs │ ├── Constants.cs │ ├── Enums │ └── EnumSample.cs │ ├── Exceptions │ └── ExceptionsSample.cs │ ├── Files │ └── FilesSample.cs │ ├── ISampleExecute.cs │ ├── MultiThreading │ ├── BackgroundWorkerSample.cs │ ├── MultithreadingSample.cs │ └── ThreadSample.cs │ ├── Patterns │ ├── Behavioral │ │ ├── ChainOfResponsibilityPattern.cs │ │ ├── ObserverPattern.cs │ │ ├── StatePattern.cs │ │ └── StrategyPattern.cs │ ├── Creational │ │ ├── AbstractFactoryPattern.cs │ │ ├── FactoryMethodPattern.cs │ │ └── SingletonPattern.cs │ ├── Other │ │ ├── RepositoryPattern.cs │ │ └── UnitOfWorkPattern.cs │ ├── PatternsSample.cs │ └── Structural │ │ ├── DecoratorPattern.cs │ │ └── FacadePattern.cs │ ├── Program.cs │ ├── Properties │ ├── AssemblyInfo.cs │ ├── OtherSettings.Designer.cs │ ├── OtherSettings.settings │ ├── Settings.Designer.cs │ └── Settings.settings │ ├── RegularExpressions │ └── RegExSample.cs │ ├── SOLID │ ├── S01-SingleResponsibilityPrinciple_SRP │ │ ├── GarageStation.cs │ │ ├── GarageUtility.cs │ │ ├── IGarageUtility.cs │ │ └── SingleResponsibilityPrincipleSample.cs │ └── S04-InversionOfControl_IoC │ │ ├── Duck.cs │ │ ├── Flys.cs │ │ ├── IDuckFly.cs │ │ ├── IDuckQuack.cs │ │ ├── InversionOfControlSample.cs │ │ └── Quacks.cs │ ├── SampleExecute.cs │ ├── Settings.cs │ ├── Settings │ ├── ConfigurationManagerSnippets.cs │ └── SettingsSample.cs │ ├── Structures │ └── StructSample.cs │ ├── SyntacticSugars │ ├── NullSample.cs │ ├── PatternMatchingSample.cs │ ├── PropertiesSample.cs │ ├── StringInterpolationSample.cs │ └── UsingSample.cs │ ├── Timing │ ├── TimingSample.cs │ └── TimingStopwatch.cs │ ├── TupleDeconstruction │ └── TupleDeconstruction.cs │ ├── Useful │ ├── GarbageCollectionSample.cs │ ├── LinqSample.cs │ ├── OverflowCheckSample.cs │ └── ResultSample.cs │ ├── UsefulClasses │ ├── CollectionInitializerSamples.cs │ ├── Dictionaries.cs │ ├── ObjectPoolSample.cs │ └── SpanSample.cs │ └── packages.config ├── LICENSE └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.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 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /CSharp Code Samples/CSharp Code Samples.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28307.102 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeSamples", "CodeSamples\CodeSamples.csproj", "{8299A09C-BCD3-4018-B0CC-853D8557E965}" 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 | {8299A09C-BCD3-4018-B0CC-853D8557E965}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {8299A09C-BCD3-4018-B0CC-853D8557E965}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {8299A09C-BCD3-4018-B0CC-853D8557E965}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {8299A09C-BCD3-4018-B0CC-853D8557E965}.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 = {D449A3F1-EC10-46E5-BF3D-F83A9EF6BE06} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Alterations/EntityConversionSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Alterations 4 | { 5 | public class EntityOne 6 | { 7 | public int ValueOne { get; set; } = 1; 8 | 9 | //implicit operators do not require explicit cast 10 | public static implicit operator EntityTwo(EntityOne entity) 11 | { 12 | var entityTwo = new EntityTwo() 13 | { 14 | ValueTwo = entity.ValueOne 15 | }; 16 | return entityTwo; 17 | } 18 | } 19 | 20 | public class EntityTwo 21 | { 22 | public int ValueTwo { get; set; } = 2; 23 | 24 | //explicit operators DOES require cast 25 | public static explicit operator EntityOne(EntityTwo entity) 26 | { 27 | var entityOne = new EntityOne() 28 | { 29 | ValueOne = entity.ValueTwo 30 | }; 31 | return entityOne; 32 | } 33 | } 34 | 35 | public class EntityConversionSample : SampleExecute 36 | { 37 | public override void Execute() 38 | { 39 | Title("EntityConversionSampleExecute"); 40 | EntityOne entityOne = new EntityOne(); 41 | EntityTwo entityTwo = new EntityTwo(); 42 | EntityOne entityOneExplicit = (EntityOne)entityTwo; 43 | EntityTwo entityTwoImplicit = entityOne; 44 | // 45 | Console.WriteLine($"Entity One: original = {entityOne.ValueOne}, explicit casting = {entityOneExplicit.ValueOne}"); 46 | Console.WriteLine($"Entity Two: original = {entityTwo.ValueTwo}, implicit casting = {entityTwoImplicit.ValueTwo}"); 47 | // 48 | Finish(); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Alterations/Extensions/ClassExtensionSample.cs: -------------------------------------------------------------------------------- 1 | using CodeSamples.Alterations.Extensions; 2 | using System; 3 | 4 | namespace CodeSamples.Alterations 5 | { 6 | public class ClassExtensionSample : SampleExecute 7 | { 8 | public override void Execute() 9 | { 10 | Title("ClassExtensionSample"); 11 | 12 | string str = "This Is A String To count All UpperCase characters."; 13 | Console.WriteLine($"String '{str}' has {str.CountUppercaseCharacters()} uppercase characters."); 14 | Console.WriteLine($"String '{str}' has {str.CountCharacters('e')} 'e' characters."); 15 | 16 | string testString = "test string"; 17 | string resultString = testString.PadRightWithString("", 5); 18 | Console.WriteLine("Original string:"); 19 | testString.WriteToConsole(); 20 | Console.WriteLine("Padded string:"); 21 | resultString.WriteToConsole(); 22 | 23 | Finish(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Alterations/Extensions/ClassExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | 7 | namespace CodeSamples.Alterations.Extensions 8 | { 9 | public static class ClassExtensions 10 | { 11 | public static int CountUppercaseCharacters(this string str) 12 | { 13 | string allCaps = string.Concat(str.Where(c => (c >= 'A' && c <= 'Z'))); 14 | return allCaps.Length; 15 | } 16 | 17 | public static int CountCharacters(this string str, char chr) 18 | { 19 | string allChars = string.Concat(str.Where(c => (c == chr))); 20 | return allChars.Length; 21 | } 22 | 23 | public static string PadRightWithString(this string value, string padding, int paddingCount) 24 | { 25 | var result = new StringBuilder(value); 26 | for (int i = 0; i < paddingCount; i++) 27 | { 28 | result.Append(padding); 29 | } 30 | return result.ToString(); 31 | } 32 | 33 | public static void WriteToConsole(this string value) 34 | { 35 | Console.WriteLine($"Contents Of String = {value}"); 36 | } 37 | 38 | public static string GetDescription(this T enumerationValue) where T : struct 39 | { 40 | Type type = enumerationValue.GetType(); 41 | if (!type.IsEnum) 42 | { 43 | throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue"); 44 | } 45 | 46 | //Tries to find a DescriptionAttribute for a potential friendly name 47 | //for the enum 48 | MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString()); 49 | if (memberInfo != null && memberInfo.Length > 0) 50 | { 51 | object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); 52 | 53 | if (attrs != null && attrs.Length > 0) 54 | { 55 | //Pull out the description value 56 | return ((DescriptionAttribute)attrs[0]).Description; 57 | } 58 | } 59 | //If we have no description attribute, just return the ToString of the enum 60 | return enumerationValue.ToString(); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Alterations/OperatorOverloadingSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Alterations 4 | { 5 | #region Calculation Class 6 | /// 7 | /// List of overloadable operators: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading 8 | /// 9 | public class CalculationClass 10 | { 11 | public int A { get; set; } 12 | 13 | #region Constructors 14 | public CalculationClass() : this(0) { } 15 | 16 | public CalculationClass(int initialValue) 17 | { 18 | A = initialValue; 19 | } 20 | #endregion 21 | 22 | #region Addition (Operator +) 23 | public static CalculationClass operator +(CalculationClass value) => value; 24 | 25 | public static CalculationClass operator +(CalculationClass firstValue, CalculationClass secondValue) 26 | { 27 | return new CalculationClass(firstValue.A + secondValue.A); 28 | } 29 | 30 | public static CalculationClass operator +(CalculationClass firstValue, int secondValue) 31 | { 32 | return firstValue + new CalculationClass(secondValue); 33 | } 34 | 35 | public static CalculationClass operator +(int firstValue, CalculationClass secondValue) 36 | { 37 | return secondValue + new CalculationClass(firstValue); 38 | } 39 | #endregion 40 | 41 | #region Subtraction (Operator -) 42 | public static CalculationClass operator -(CalculationClass value) => new CalculationClass(-value.A); 43 | 44 | public static CalculationClass operator -(CalculationClass firstValue, CalculationClass secondValue) 45 | { 46 | return new CalculationClass(firstValue.A - secondValue.A); 47 | } 48 | #endregion 49 | 50 | public static CalculationClass operator *(CalculationClass firstValue, CalculationClass secondValue) 51 | { 52 | return new CalculationClass(firstValue.A * secondValue.A); 53 | } 54 | 55 | public static CalculationClass operator /(CalculationClass firstValue, CalculationClass secondValue) 56 | { 57 | return new CalculationClass(firstValue.A / secondValue.A); 58 | } 59 | 60 | public static bool operator true(CalculationClass value) 61 | { 62 | return value.A != 0; 63 | } 64 | 65 | public static bool operator false(CalculationClass value) 66 | { 67 | return value.A == 0; 68 | } 69 | 70 | #region Equality 71 | public static Boolean operator ==(CalculationClass firstValue, CalculationClass secondValue) 72 | { 73 | return (firstValue.A == secondValue.A); 74 | } 75 | 76 | public static Boolean operator !=(CalculationClass firstValue, CalculationClass secondValue) 77 | { 78 | return (firstValue.A != secondValue.A); 79 | } 80 | #endregion 81 | 82 | #region Comparing 83 | 84 | #region Operator > 85 | public static Boolean operator >(CalculationClass firstValue, CalculationClass secondValue) 86 | { 87 | return (firstValue.A > secondValue.A); 88 | } 89 | 90 | public static Boolean operator >(CalculationClass firstValue, int secondValue) 91 | { 92 | return (firstValue.A > secondValue); 93 | } 94 | 95 | public static Boolean operator >(int firstValue, CalculationClass secondValue) 96 | { 97 | return (firstValue > secondValue.A); 98 | } 99 | #endregion 100 | 101 | #region Operator < 102 | public static Boolean operator <(CalculationClass firstValue, CalculationClass secondValue) 103 | { 104 | return (firstValue.A < secondValue.A); 105 | } 106 | 107 | public static Boolean operator <(CalculationClass firstValue, int secondValue) 108 | { 109 | return (firstValue.A < secondValue); 110 | } 111 | 112 | public static Boolean operator <(int firstValue, CalculationClass secondValue) 113 | { 114 | return (firstValue < secondValue.A); 115 | } 116 | #endregion 117 | 118 | #region Operator >= 119 | public static Boolean operator >=(CalculationClass firstValue, CalculationClass secondValue) 120 | { 121 | return (firstValue.A >= secondValue.A); 122 | } 123 | #endregion 124 | 125 | #region Operator <= 126 | public static Boolean operator <=(CalculationClass firstValue, CalculationClass secondValue) 127 | { 128 | return (firstValue.A <= secondValue.A); 129 | } 130 | #endregion 131 | 132 | #endregion 133 | 134 | public override bool Equals(object obj) 135 | { 136 | var value = obj as CalculationClass; 137 | if (obj == null) 138 | { 139 | return false; 140 | } 141 | bool result = this.A == value.A; 142 | return result; 143 | } 144 | 145 | public override int GetHashCode() 146 | { 147 | return this.ToString().GetHashCode(); 148 | } 149 | 150 | public override string ToString() 151 | { 152 | return String.Format($"{this.A}"); 153 | } 154 | } 155 | #endregion 156 | 157 | public class OperatorOverloadingSample : SampleExecute 158 | { 159 | public override void Execute() 160 | { 161 | Title("OperatorOverloadingSampleExecute"); 162 | 163 | CalculationClass A = new CalculationClass() { A = 100 }; 164 | CalculationClass B = new CalculationClass() { A = 3 }; 165 | CalculationClass C = new CalculationClass() { A = 0 }; 166 | var sum = A + B; 167 | var diff = A - B; 168 | var product = A * B; 169 | var coeff = A / B; 170 | var equal = A == B; 171 | var notEqual = A != B; 172 | // 173 | Console.WriteLine($"Original => A = {A}, B = {B}"); 174 | Console.WriteLine($"Sum => A + B = {sum}"); 175 | Console.WriteLine($"Diff => A - B = {diff}"); 176 | Console.WriteLine($"Product => A * B = {product}"); 177 | Console.WriteLine($"Coeff => A / B = {coeff}"); 178 | Console.WriteLine($"Equal => A == B = {equal}"); 179 | Console.WriteLine($"notEqual => A != B = {notEqual}"); 180 | Console.WriteLine($"true/false => A = {(A ? "true" : "false")}"); 181 | Console.WriteLine($"true/false => B = {(B ? "true" : "false")}"); 182 | Console.WriteLine($"true/false => C (=) = {(C ? "true" : "false")}"); 183 | // 184 | Finish(); 185 | } 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 |
7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | StringValue 20 | 21 | 22 | 0 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 0 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Attributes/ConditionalSample.cs: -------------------------------------------------------------------------------- 1 | #define CONDITION1 2 | #define CONDITION2 3 | 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace CodeSamples.Attributes 8 | { 9 | public class ConditionalSample : SampleExecute 10 | { 11 | [Conditional("CONDITION1")] 12 | private void MethodCondition1() 13 | { 14 | Console.WriteLine("MethodCondition1"); 15 | } 16 | 17 | [Conditional("CONDITION2")] 18 | private void MethodCondition2() 19 | { 20 | Console.WriteLine("MethodCondition2"); 21 | } 22 | 23 | [Conditional("CONDITION3")] 24 | private void MethodCondition3() 25 | { 26 | Console.WriteLine("MethodCondition3"); 27 | } 28 | 29 | [Conditional("CONDITION1"), Conditional("CONDITION2")] 30 | private void MethodCondition1or2() 31 | { 32 | Console.WriteLine("MethodCondition1or2"); 33 | } 34 | 35 | [Conditional("CONDITION1"), Conditional("CONDITION3")] 36 | private void MethodCondition1or3() 37 | { 38 | Console.WriteLine("MethodCondition1or3"); 39 | } 40 | 41 | public override void Execute() 42 | { 43 | Title("ConditionalSampleExecute"); 44 | MethodCondition1(); 45 | MethodCondition2(); 46 | MethodCondition3(); 47 | MethodCondition1or2(); 48 | MethodCondition1or3(); 49 | Finish(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Attributes/CustomAttributesSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Attributes 4 | { 5 | [AttributeUsage(AttributeTargets.Property)] 6 | internal sealed class DefaultValueAttribute : Attribute 7 | { 8 | private int _defaultValue; 9 | 10 | public DefaultValueAttribute(int defaultValue) 11 | { 12 | _defaultValue = defaultValue; 13 | } 14 | } 15 | 16 | 17 | public class CustomAttributesSample 18 | { 19 | [DefaultValue(5)] 20 | public int SomeProperty { get; set; } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Attributes/DebuggingSample.cs: -------------------------------------------------------------------------------- 1 | #if !DEBUG 2 | #define RELEASE 3 | #else 4 | #define WERE_OK 5 | #endif 6 | 7 | #if DEBUG 8 | #warning This is good as it is run in Debug mode 9 | #endif 10 | 11 | #if (DEBUG && WERE_OK) 12 | #undef WERE_OK 13 | #endif 14 | 15 | #if !DEBUG 16 | #error This should only be run in Debug mode 17 | #endif 18 | 19 | using System; 20 | using System.Diagnostics; 21 | 22 | namespace CodeSamples.Attributes 23 | { 24 | sealed class FullName 25 | { 26 | public FullName(string firstName, string lastName) 27 | { 28 | FirstName = firstName; 29 | LastName = lastName; 30 | } 31 | 32 | public string FirstName { get; set; } 33 | public string LastName { get; set; } 34 | } 35 | 36 | /// 37 | /// 38 | /// DebuggerBrowsableState.Collapsed - This signifies that the default behaviour should be used for the decorated member and 39 | /// gives the equivalent results as when the attribute is omitted. When viewed in a debugging tool the member is visible 40 | /// and can be expanded to allow access to any further members that it contains. 41 | /// 42 | /// 43 | /// DebuggerBrowsableState.Never - This indicates that the member should not be displayed in debugging windows. The member is 44 | /// hidden from view completely. 45 | /// 46 | /// 47 | /// DebuggerBrowsableState.RootHidden - This signifies that the member should not be visible but that its own members should be. 48 | /// The members of the hidden item appear as if they were one level higher in the hierarchy of values. This setting is useful 49 | /// for members that are used only to store structured information, such as collection types or some data objects. 50 | /// 51 | /// 52 | sealed class DebuggerExamplesDebuggerBrowsable 53 | { 54 | [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] 55 | public string StandardProperty { get; set; } 56 | 57 | [DebuggerBrowsable(DebuggerBrowsableState.Never)] 58 | public string HiddenInDebuggerWindow { get; set; } 59 | 60 | [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] 61 | public FullName OnlyPropertiesOfClassVisibleInDebuggerWindow { get; set; } 62 | } 63 | 64 | [DebuggerDisplay("StringValue = {StringValue}, IntValue = {GetIntValue()}")] 65 | sealed class DebuggerExamplesDebuggerDisplay 66 | { 67 | public string StringValue { get; set; } = "SomeStringValue"; 68 | public int GetIntValue() 69 | { 70 | return 5 * 2; 71 | } 72 | 73 | /// 74 | /// Also see class 75 | /// 76 | [Conditional("DEBUG")] 77 | public void ExecuteOnlyInDebugMode() 78 | { 79 | Console.WriteLine("Executed in DEBUG mode"); 80 | } 81 | 82 | /// 83 | /// Also see class 84 | /// 85 | [Conditional("RELEASE")] 86 | public void ExecuteOnlyInReleaseMode() 87 | { 88 | Console.WriteLine("Executed in RELEASE mode"); 89 | } 90 | 91 | #if DEBUG 92 | public void CompileOnlyWhenDebugDefined() 93 | { 94 | Console.WriteLine("Compiled and Executed in DEBUG mode"); 95 | } 96 | #endif 97 | 98 | #if !DEBUG 99 | public void CompileOnlyWhenDebugNotDefined() 100 | { 101 | Console.WriteLine($"Compiled and Executed in RELEASE mode"); 102 | } 103 | #endif 104 | 105 | public void RuntimeDebuggerAttached() 106 | { 107 | string debuggerAttached = Debugger.IsAttached ? "is" : "is not"; 108 | Console.WriteLine($"Runtime Debugger Checking: Debugger {debuggerAttached} attached"); 109 | Console.WriteLine($"Assuming we're running {(Debugger.IsAttached ? "from IDE" : "standalone")}"); 110 | } 111 | 112 | [DebuggerStepThrough] 113 | public void DebuggerStepThroughMethod() 114 | { 115 | Console.WriteLine($"Debugger stepped through this method."); 116 | } 117 | 118 | /// 119 | /// Trace and debug messages 120 | /// This shows in Immediate Window (Ctrl + Alt + I) 121 | /// e.g. Input in Immediate window (after build): ?(new DebuggingSample().Execute()) 122 | /// 123 | public void ImmediateWindowMessages() 124 | { 125 | Trace.WriteLine("Some Trace messages to follow:"); 126 | Trace.IndentSize = 2; 127 | Trace.Indent(); 128 | Trace.TraceInformation("This is Trace information."); 129 | Trace.Indent(); 130 | Trace.TraceInformation("This is Trace information - indented."); 131 | Trace.Unindent(); 132 | Trace.TraceWarning("This is Trace Warning."); 133 | Trace.TraceError("This is Trace Error."); 134 | Trace.Unindent(); 135 | Trace.Flush(); 136 | // 137 | Debug.WriteLine("This is Debug Line."); 138 | } 139 | } 140 | 141 | public class DebuggingSample : SampleExecute 142 | { 143 | public override void Execute() 144 | { 145 | Title("DebuggingSampleExecute"); 146 | Section("Creating class (if breakpoint is used here, debugger output will be formatted as in DebuggerDisplay())"); 147 | 148 | DebuggerExamplesDebuggerDisplay debuggerExample = new DebuggerExamplesDebuggerDisplay(); 149 | //set breakpoint on next line and hover over "debuggerExample" variable 150 | debuggerExample.DebuggerStepThroughMethod(); 151 | debuggerExample.ExecuteOnlyInDebugMode(); 152 | debuggerExample.ExecuteOnlyInReleaseMode(); 153 | debuggerExample.RuntimeDebuggerAttached(); 154 | 155 | Section("Immediate Window Messages"); 156 | debuggerExample.ImmediateWindowMessages(); 157 | 158 | Finish(); 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Attributes/ObsoleteSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Attributes 4 | { 5 | sealed class ObsoleteExamples 6 | { 7 | //with "false" as the last parameter, compiler warning will be generated, if property is used anywhere 8 | [Obsolete("This property is obsolete.", false)] 9 | public string OldStringValue { get; set; } 10 | 11 | //with "true" as the last parameter, compiler error will be generated, if method is called anywhere 12 | [Obsolete("This method is obsolete.", true)] 13 | public int OldGetIntValue() 14 | { 15 | return 5 * 2; 16 | } 17 | } 18 | 19 | public class ObsoleteSample : SampleExecute 20 | { 21 | public override void Execute() 22 | { 23 | Title("ObsoleteSampleExecute"); 24 | Section("Creating class (messages only at compile time)"); 25 | ObsoleteExamples obsoleteExample = new ObsoleteExamples(); 26 | //following line produces compiler warning 27 | obsoleteExample.OldStringValue = String.Empty; 28 | //following line produces compiler error, if uncommented 29 | //int value = obsoleteExample.OldGetIntValue(); 30 | Finish(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Classes/AccessModifiersSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Classes 4 | { 5 | /// 6 | /// Only »public« and »internal« (default, if no modifier specified) can be used in namespace level 7 | /// Source: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers 8 | /// 9 | internal class InternalClass 10 | { 11 | /// 12 | /// public: The type or member can be accessed by any other code in the same assembly or another assembly that references it. 13 | /// Usage: general, when member has to be accessible everywhere 14 | /// 15 | public int PublicMember = 0; 16 | 17 | /// 18 | /// private: The type or member can be accessed only by code in the same class or struct. 19 | /// Usage: general, when member has to stay hidden 20 | /// 21 | private int PrivateMember = 0; 22 | 23 | /// 24 | /// protected: The type or member can be accessed only by code in the same class, or in a class that is derived from that class. 25 | /// Usage: e.g. derived class can access member of base abstract class, but no other class can access it 26 | /// 27 | protected int ProtectedMember = 0; 28 | 29 | /// 30 | /// internal: The type or member can be accessed by any code in the same assembly, but not from another assembly. 31 | /// Usage: general, access from same assembly (exe or dll); it's default modifier (for class or struct) if no other is set 32 | /// 33 | internal int InternalMember = 0; 34 | 35 | /// 36 | /// protected internal: The type or member can be accessed by any code in the assembly in which it's declared, or from within a derived class in another assembly. 37 | /// 38 | protected internal int ProtectedInternalMember = 0; 39 | 40 | /// 41 | /// private protected: The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class. 42 | /// 43 | private protected int PrivateProtectedMember = 0; 44 | } 45 | 46 | /// 47 | /// Members can have all modifiers, even if it is a child class 48 | /// 49 | public class PublicClass 50 | { 51 | private class PrivateClassInAnotherClass 52 | { 53 | 54 | } 55 | 56 | protected class ProtectedClassInAnotherClass 57 | { 58 | 59 | } 60 | 61 | private protected int PrivateProtectedMember = 0; 62 | } 63 | 64 | public class AccessModifiersSample : SampleExecute 65 | { 66 | public override void Execute() 67 | { 68 | throw new NotImplementedException(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Classes/AnonymousTypesSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Classes 4 | { 5 | public class AnonymousTypesSample : SampleExecute 6 | { 7 | /// 8 | /// Creates anonymous type (object) with properties Name, Lastname and Age 9 | /// 10 | public override void Execute() 11 | { 12 | Title("AnonymousTypesSampleExecute"); 13 | var anonymousObject = new { Name = "Foo", Lastname = "Bar", Age = 13 }; 14 | Console.WriteLine($"anonymousObject(), Name = {anonymousObject.Name}, Lastname = {anonymousObject.Lastname}, Age = {anonymousObject.Age}"); 15 | Finish(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Classes/CallerInfoSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Classes 4 | { 5 | public class CallerInfoSample : SampleExecute 6 | { 7 | public void TraceMessage(string message, 8 | [System.Runtime.CompilerServices.CallerMemberName] string memberName = "", 9 | [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "", 10 | [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) 11 | { 12 | Console.WriteLine($"Message = {message}"); 13 | Console.WriteLine($"Member (Method) Name = {memberName}"); 14 | Console.WriteLine($"Source File Path = {sourceFilePath}"); 15 | Console.WriteLine($"Line Number = {sourceLineNumber}"); 16 | } 17 | 18 | public override void Execute() 19 | { 20 | Title("CallerInfoSampleExecute"); 21 | TraceMessage("Tracing this call..."); 22 | Finish(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Classes/ClassAndMethodNamesSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Classes 4 | { 5 | public class ClassAndMethodNamesSample : SampleExecute 6 | { 7 | public override void Execute() 8 | { 9 | string className = this.GetType().Name; 10 | string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; 11 | 12 | Title("ClassAndMethodNamesSampleExecute"); 13 | Console.WriteLine($"This Class Name = {className}"); 14 | Console.WriteLine($"This Method Name = {methodName}"); 15 | Finish(); 16 | } 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Classes/ConstructorChainingSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Classes 4 | { 5 | public class SampleClass 6 | { 7 | public SampleClass() : this(0) { Console.WriteLine("Default Constructor"); } 8 | public SampleClass(int param) : this(0, "string param") { Console.WriteLine("Constructor with one parameter"); } 9 | public SampleClass(int paramInt, string paramStr) { Console.WriteLine("Constructor with two parameters"); } 10 | } 11 | 12 | public class ConstructorChainingSample : SampleExecute 13 | { 14 | public override void Execute() 15 | { 16 | Title("ConstructorChainingSampleExecute"); 17 | Section("Creating class by calling constructor with no params"); 18 | SampleClass classNoParams = new SampleClass(); 19 | LineBreak(); 20 | // 21 | Section("Creating class by calling constructor with 1 params"); 22 | SampleClass classOneParam = new SampleClass(1); 23 | LineBreak(); 24 | // 25 | Section("Creating class by calling constructor with 2 params"); 26 | SampleClass classTwoParams = new SampleClass(3, "Yo! This is a story all about how..."); 27 | // 28 | Finish(); 29 | 30 | // Output: 31 | // 32 | // ConstructorChainingSampleExecute 33 | // ============================================================ 34 | // Creating class by calling constructor with no params 35 | // ============================================================ 36 | // Constructor with two parameters 37 | // Constructor with one parameter 38 | // Default Constructor 39 | // ============================================================ 40 | // Creating class by calling constructor with 1 params 41 | // ============================================================ 42 | // Constructor with two parameters 43 | // Constructor with one parameter 44 | // ============================================================ 45 | // Creating class by calling constructor with 2 params 46 | // ============================================================ 47 | // Constructor with two parameters 48 | // ============================================================ 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Classes/GenericsSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.ObjectModel; 3 | 4 | 5 | /// 6 | /// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters 7 | /// 8 | namespace CodeSamples.Classes 9 | { 10 | #region Support stuff for Snippets 11 | internal enum EnumType 12 | { 13 | No, 14 | Yes 15 | } 16 | 17 | internal struct StructType 18 | { 19 | public string Something; 20 | public int SomethingElse; 21 | } 22 | 23 | internal class ClassWithParameterlessConstructor 24 | { 25 | public ClassWithParameterlessConstructor() 26 | { 27 | Console.WriteLine($"Hello! I am {this.GetType().Name}."); 28 | } 29 | } 30 | 31 | internal class ClassWithParameterConstructor 32 | { 33 | public ClassWithParameterConstructor(int count) 34 | { 35 | Console.WriteLine($"Hello! I am {this.GetType().Name}."); 36 | } 37 | } 38 | 39 | internal interface ISomeInterface 40 | { 41 | void Go(); 42 | } 43 | 44 | internal class ClassFromSomeInterface : ISomeInterface 45 | { 46 | public void Go() 47 | { 48 | Console.WriteLine($"Hello! I am {this.GetType().Name}."); 49 | } 50 | } 51 | 52 | internal abstract class SomeBaseClass 53 | { 54 | public abstract void Go(); 55 | } 56 | 57 | internal class SomeClassFromBaseClass : SomeBaseClass 58 | { 59 | public override void Go() 60 | { 61 | Console.WriteLine($"Hello! I am {this.GetType().Name}."); 62 | } 63 | } 64 | #endregion 65 | 66 | internal class GenericClass 67 | { 68 | public void Go() 69 | { 70 | Console.WriteLine($"Hello! I am {this.GetType().Name} and my main element is of type {typeof(T)}."); 71 | } 72 | } 73 | 74 | /// 75 | /// The type argument must be a non-nullable value type. For information about 76 | /// nullable value types, see Nullable value types. Because all value types have 77 | /// an accessible parameterless constructor, the struct constraint implies the new() 78 | /// constraint and can't be combined with the new() constraint. You can't combine 79 | /// the struct constraint with the unmanaged constraint. 80 | /// 81 | /// 82 | internal class GenericClassStruct where T : struct 83 | { 84 | public void Go() 85 | { 86 | Console.WriteLine($"Hello! I am {this.GetType().Name} and my main element is of type {typeof(T)}."); 87 | } 88 | } 89 | 90 | /// 91 | /// The type argument must be a reference type. This constraint applies also to any 92 | /// class, interface, delegate, or array type. In a nullable context in C# 8.0 or 93 | /// later, T must be a non-nullable reference type. 94 | /// 95 | /// 96 | internal class GenericClassClass where T : class 97 | { 98 | public void Go() 99 | { 100 | Console.WriteLine($"Hello! I am {this.GetType().Name} and my main element is of type {typeof(T)}."); 101 | } 102 | } 103 | 104 | /// 105 | /// The type argument must have a public parameterless constructor. When used together 106 | /// with other constraints, the new() constraint must be specified last. The new() 107 | /// constraint can't be combined with the struct and unmanaged constraints. 108 | /// 109 | /// 110 | internal class GenericClassNew where T : new() 111 | { 112 | public void Go() 113 | { 114 | Console.WriteLine($"Hello! I am {this.GetType().Name} and my main element is of type {typeof(T)}."); 115 | } 116 | } 117 | 118 | /// 119 | /// The type argument must be a non-nullable unmanaged type. The unmanaged constraint 120 | /// implies the struct constraint and can't be combined with either the struct or new() 121 | /// constraints. 122 | /// 123 | /// 124 | internal class GenericClassUnmanaged where T : unmanaged 125 | { 126 | public void Go() 127 | { 128 | Console.WriteLine($"Hello! I am {this.GetType().Name} and my main element is of type {typeof(T)}."); 129 | } 130 | } 131 | 132 | /// 133 | /// The type argument must be or derive from the specified base class. In a nullable context 134 | /// in C# 8.0 and later, T must be a non-nullable reference type derived from the specified base class. 135 | /// 136 | /// 137 | internal class GenericClassBaseClass where T : SomeBaseClass 138 | { 139 | public void Go() 140 | { 141 | Console.WriteLine($"Hello! I am {this.GetType().Name} and my main element is of type {typeof(T)}."); 142 | } 143 | } 144 | 145 | /// 146 | /// The type argument must be or implement the specified interface. Multiple interface constraints 147 | /// can be specified. The constraining interface can also be generic. In a nullable context in C# 8.0 148 | /// and later, T must be a non-nullable type that implements the specified interface. 149 | /// 150 | /// 151 | internal class GenericClassInterface where T : ISomeInterface 152 | { 153 | public void Go() 154 | { 155 | Console.WriteLine($"Hello! I am {this.GetType().Name} and my main element is of type {typeof(T)}."); 156 | } 157 | } 158 | 159 | internal class GenericClassOnlyEnum where T : System.Enum 160 | { 161 | public void Go() 162 | { 163 | Console.WriteLine($"Hello! I am {this.GetType().Name} and my main element is of type {typeof(T)}."); 164 | } 165 | } 166 | 167 | internal class GenericClassCombined where T : unmanaged where U : ISomeInterface 168 | { 169 | public void Go() 170 | { 171 | Console.WriteLine($"Hello! I am {this.GetType().Name} and my elements are of type {typeof(T)} and {typeof(U)}."); 172 | } 173 | } 174 | 175 | public class GenericsSample : SampleExecute 176 | { 177 | public override void Execute() 178 | { 179 | Title("GenericSampleExecute"); 180 | 181 | var genericClass1 = new GenericClass(); 182 | genericClass1.Go(); 183 | 184 | var genericClass2 = new GenericClass(); 185 | genericClass2.Go(); 186 | 187 | var genericClass3 = new GenericClass(); 188 | genericClass3.Go(); 189 | 190 | var genericClassEnum = new GenericClassStruct(); 191 | genericClassEnum.Go(); 192 | 193 | var genericClassStruct = new GenericClassStruct(); 194 | genericClassStruct.Go(); 195 | 196 | var genericClassClass = new GenericClassClass>(); 197 | genericClassClass.Go(); 198 | 199 | var genericClassNew = new GenericClassNew(); 200 | genericClassNew.Go(); 201 | 202 | //this producess error, because constructor has parameter: 203 | //Error CS0310 'ClassWithParameterConstructor' must be a non-abstract type with a 204 | //public parameterless constructor in order to use it as parameter 'T' in the generic 205 | //type or method 'GenericClassNew' 206 | //var genericClassNewParam = new GenericClassNew(); 207 | //genericClassNewParam.Go(); 208 | 209 | var genericClassUnmanaged = new GenericClassUnmanaged(); 210 | genericClassUnmanaged.Go(); 211 | 212 | //this producess error, because ClassWithParameterlessConstructor in not unmanaged type: 213 | ///Error CS8377 The type 'ClassWithParameterlessConstructor' must be a non-nullable 214 | ///value type, along with all fields at any level of nesting, in order to use it as 215 | ///parameter 'T' in the generic type or method 'GenericClassUnmanaged' 216 | //var genericClassUnmanaged2 = new GenericClassUnmanaged(); 217 | //genericClassUnmanaged2.Go(); 218 | 219 | var genericClassInterface1 = new GenericClassInterface(); 220 | genericClassInterface1.Go(); 221 | 222 | var genericClassInterface2 = new GenericClassInterface(); 223 | genericClassInterface2.Go(); 224 | 225 | var genericClassBaseClass1 = new GenericClassBaseClass(); 226 | genericClassBaseClass1.Go(); 227 | 228 | var genericClassBaseClass2 = new GenericClassBaseClass(); 229 | genericClassBaseClass2.Go(); 230 | 231 | Finish(); 232 | } 233 | } 234 | } 235 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Classes/StaticSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Classes 4 | { 5 | internal static class StaticClass 6 | { 7 | static readonly int Constant = 10; 8 | 9 | static StaticClass() 10 | { 11 | Console.WriteLine($"Called static constructor of StaticClass, property {nameof(Constant)} = {Constant}"); 12 | } 13 | 14 | public static void Something() 15 | { 16 | Console.WriteLine($"Something is going on..."); 17 | } 18 | } 19 | 20 | internal class RegularClassWithStaticMethods 21 | { 22 | public RegularClassWithStaticMethods() 23 | { 24 | Console.WriteLine("Hey! You woke me up! What do you want? I'm just a regular constructor..."); 25 | } 26 | 27 | /// 28 | /// Static constructor is only called once, even when instantiating a class 29 | /// 30 | static RegularClassWithStaticMethods() 31 | { 32 | Console.WriteLine("Hello! You have reached static constructor. How may I help you?"); 33 | } 34 | 35 | public void RegularMethod() 36 | { 37 | Console.WriteLine("Meh! I'm just a regular method!"); 38 | } 39 | 40 | public static void StaticMethod() 41 | { 42 | Console.WriteLine("Oh yeah! I'm a static method!"); 43 | } 44 | } 45 | 46 | public class StaticSample : SampleExecute 47 | { 48 | public override void Execute() 49 | { 50 | Title("StaticSampleExecute"); 51 | 52 | Section("Static Class"); 53 | StaticClass.Something(); 54 | 55 | Section("Regular Class, Regular method"); 56 | var regularClass = new RegularClassWithStaticMethods(); 57 | regularClass.RegularMethod(); 58 | 59 | Section("Regular Class, Static method"); 60 | RegularClassWithStaticMethods.StaticMethod(); 61 | 62 | Finish(); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/ClipboardUse/ClipboardSample.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Windows.Forms; 4 | 5 | namespace CodeSamples.ClipboardUse 6 | { 7 | internal class ClipboardSample : SampleExecute 8 | { 9 | //https://docs.microsoft.com/en-us/windows/win32/com/dropeffect-constants 10 | // Constant Value Description 11 | //=================================================================== 12 | //DROPEFFECT_NONE 0 Drop target cannot accept the data. 13 | //DROPEFFECT_COPY 1 Drop results in a copy. The original data is untouched by the drag source. 14 | //DROPEFFECT_MOVE 2 Drag source should remove the data. 15 | //DROPEFFECT_LINK 4 Drag source should create a link to the original data. 16 | //DROPEFFECT_SCROLL 0x80000000 Scrolling is about to start or is currently occurring in the target. This value is used in addition to the other values. 17 | 18 | 19 | /// 20 | /// CFSTR_PREFERREDDROPEFFECT 21 | /// 22 | public const string FileDropEffect = "Preferred DropEffect"; 23 | 24 | /// 25 | /// DROPEFFECT_MOVE 26 | /// 27 | public const uint DropEffectMove = (uint)0x00000002; 28 | 29 | /// 30 | /// DROPEFFECT_COPY 31 | /// 32 | public const uint DropEffectCopy = (uint)0x00000005; 33 | 34 | /// 35 | /// DROPEFFECT_SCROLL 36 | /// 37 | public const uint DropEffectScroll = (uint)0x80000000; 38 | 39 | private bool HasFilesInClipboard() 40 | { 41 | return Clipboard.GetDataObject().GetDataPresent(DataFormats.FileDrop); 42 | } 43 | 44 | private void CopyFilesToClipboard(List filesToCopy, bool cutOperation) 45 | { 46 | if (filesToCopy.Count != 0) 47 | { 48 | string[] files = new string[filesToCopy.Count]; 49 | filesToCopy.CopyTo(files, 0); 50 | 51 | IDataObject data = new DataObject(DataFormats.FileDrop, files); 52 | //or: 53 | //IDataObject data = new DataObject(); 54 | //data.SetData("FileDrop", true, files); 55 | 56 | using (MemoryStream memory = new MemoryStream(sizeof(uint))) 57 | { 58 | var writer = new BinaryWriter(memory); 59 | writer.Write((cutOperation ? DropEffectMove : DropEffectCopy)); 60 | 61 | data.SetData(FileDropEffect, memory); 62 | Clipboard.SetDataObject(data); 63 | } 64 | } 65 | } 66 | 67 | private List PasteFilesFromClipboard() 68 | { 69 | var result = new List(); 70 | 71 | if (!HasFilesInClipboard()) return result; 72 | 73 | IDataObject data = Clipboard.GetDataObject(); 74 | 75 | string[] files = (string[])data.GetData(DataFormats.FileDrop); 76 | MemoryStream stream = (MemoryStream)data.GetData(FileDropEffect, true); 77 | 78 | var reader = new BinaryReader(stream); 79 | 80 | uint flags = reader.ReadUInt32(); 81 | 82 | if ((flags & DropEffectMove) != DropEffectMove && (flags & DropEffectCopy) != DropEffectCopy) 83 | return result; 84 | 85 | bool moveFiles = ((flags & DropEffectMove) == DropEffectMove); 86 | 87 | foreach (string file in files) 88 | { 89 | result.Add(file); 90 | } 91 | 92 | return result; 93 | } 94 | 95 | public override void Execute() 96 | { 97 | Title("ClipboardSampleExecute"); 98 | 99 | Finish(); 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/CodeSamples.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {8299A09C-BCD3-4018-B0CC-853D8557E965} 8 | Exe 9 | CodeSamples 10 | CodeSamples 11 | v4.6.2 12 | 512 13 | true 14 | true 15 | 16 | 17 | 18 | AnyCPU 19 | true 20 | full 21 | false 22 | bin\Debug\ 23 | DEBUG;TRACE 24 | prompt 25 | 4 26 | latest 27 | 28 | 29 | AnyCPU 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | 40 | ..\packages\System.Collections.Specialized.4.3.0\lib\net46\System.Collections.Specialized.dll 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | ..\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | True 105 | True 106 | OtherSettings.settings 107 | 108 | 109 | True 110 | True 111 | Settings.settings 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | SettingsSingleFileGenerator 152 | OtherSettings.Designer.cs 153 | 154 | 155 | SettingsSingleFileGenerator 156 | Settings.Designer.cs 157 | 158 | 159 | 160 | 161 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Comparing/CompareSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | 5 | namespace CodeSamples.Comparing 6 | { 7 | public class CompareSample : SampleExecute 8 | { 9 | private void EquatableAddToList(Collection list, EquatableSample item) 10 | { 11 | if (!list.Contains(item)) 12 | { 13 | list.Add(item); 14 | Console.WriteLine($"Added Sample {item.ToString()}"); 15 | } 16 | else 17 | { 18 | Console.WriteLine($"Sample '{item.ToString()}' already in list; not added"); 19 | } 20 | } 21 | 22 | private void EquatableSample() 23 | { 24 | var list = new Collection(); 25 | 26 | var item1 = new EquatableSample() { IntProperty = 1, StringProperty = "One" }; 27 | var item2 = new EquatableSample() { IntProperty = 1, StringProperty = "Two" }; 28 | var item3 = new EquatableSample() { IntProperty = 3, StringProperty = "Three" }; 29 | var item4 = new EquatableSample() { IntProperty = 1, StringProperty = "One" }; 30 | 31 | EquatableAddToList(list, item1); 32 | EquatableAddToList(list, item2); 33 | EquatableAddToList(list, item3); 34 | EquatableAddToList(list, item4); 35 | } 36 | 37 | private void EqualityComparerAddToList(Dictionary list, EqualityComparerSample item) 38 | { 39 | try 40 | { 41 | list.Add(item, item.StringProperty); 42 | Console.WriteLine($"Added Sample {item.ToString()}"); 43 | } 44 | catch (ArgumentException) 45 | { 46 | Console.WriteLine($"Sample '{item.ToString()}' already in list; not added"); 47 | } 48 | } 49 | 50 | private void EqualityComparerSample() 51 | { 52 | //IEqualityComparer is only for dictionaries 53 | var list = new Dictionary(new EqualityComparer()); 54 | 55 | var item1 = new EqualityComparerSample() { IntProperty = 1, StringProperty = "One" }; 56 | var item2 = new EqualityComparerSample() { IntProperty = 1, StringProperty = "Two" }; 57 | var item3 = new EqualityComparerSample() { IntProperty = 3, StringProperty = "Three" }; 58 | var item4 = new EqualityComparerSample() { IntProperty = 1, StringProperty = "One" }; 59 | 60 | EqualityComparerAddToList(list, item1); 61 | EqualityComparerAddToList(list, item2); 62 | EqualityComparerAddToList(list, item3); 63 | EqualityComparerAddToList(list, item4); 64 | } 65 | 66 | public override void Execute() 67 | { 68 | Title("CompareSampleExecute"); 69 | LineBreak(); 70 | Section("IEquatable Sample"); 71 | EquatableSample(); 72 | LineBreak(); 73 | Section("IEqualityComparer Sample"); 74 | EqualityComparerSample(); 75 | LineBreak(); 76 | Finish(); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Comparing/EqualityComparer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace CodeSamples.Comparing 4 | { 5 | public class EqualityComparer : IEqualityComparer 6 | { 7 | public bool Equals(EqualityComparerSample x, EqualityComparerSample y) 8 | { 9 | if (x is null && y is null) return true; 10 | if (x is null || y is null) return false; 11 | return (x.IntProperty == y.IntProperty && x.StringProperty == y.StringProperty); 12 | } 13 | 14 | public int GetHashCode(EqualityComparerSample obj) 15 | { 16 | return obj.IntProperty.GetHashCode() ^ obj.StringProperty.GetHashCode(); 17 | } 18 | } 19 | 20 | public class EqualityComparerSample 21 | { 22 | public int IntProperty { get; set; } 23 | public string StringProperty { get; set; } 24 | 25 | public override string ToString() 26 | { 27 | return $"Int = {IntProperty}, String = {StringProperty}"; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Comparing/Equatable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Comparing 4 | { 5 | public sealed class EquatableSample : IEquatable 6 | { 7 | public int IntProperty { get; set; } 8 | public string StringProperty { get; set; } 9 | 10 | public bool Equals(EquatableSample other) 11 | { 12 | if (other is null) return false; 13 | return (other.IntProperty == IntProperty && other.StringProperty == StringProperty); 14 | } 15 | 16 | public override string ToString() 17 | { 18 | return $"Int = {IntProperty}, String = {StringProperty}"; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/ConditionalDefines/ConditionalDefinesSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.ConditionalDefines 4 | { 5 | public class ConditionalDefinesSample : SampleExecute 6 | { 7 | public override void Execute() 8 | { 9 | Title("ConditionalDefinesSampleExecute"); 10 | 11 | //for these comments see "Task List" Tab below 12 | 13 | //TODO Todo comment for Task List; this should be done asap 14 | 15 | //HACK Hack comment for Task List; Ugly hack...repair later 16 | 17 | //UNDONE Undone comment for Task List; Something was broken 18 | 19 | Section(".NET Framework"); 20 | 21 | #if NETFRAMEWORK 22 | Console.WriteLine("NETFRAMEWORK"); 23 | #endif 24 | #if NET20 25 | Console.WriteLine("NET20"); 26 | #elif NET35 27 | Console.WriteLine("NET35"); 28 | #elif NET40 29 | Console.WriteLine("NET40"); 30 | #elif NET45 31 | Console.WriteLine("NET45"); 32 | #elif NET451 33 | Console.WriteLine("NET451"); 34 | #elif NET452 35 | Console.WriteLine("NET452"); 36 | #elif NET46 37 | Console.WriteLine("NET46"); 38 | #elif NET461 39 | Console.WriteLine("NET461"); 40 | #elif NET462 41 | Console.WriteLine("NET462"); 42 | #elif NET47 43 | Console.WriteLine("NET47"); 44 | #elif NET471 45 | Console.WriteLine("NET471"); 46 | #elif NET472 47 | Console.WriteLine("NET472"); 48 | #elif NET48 49 | Console.WriteLine("NET48"); 50 | #else 51 | Console.WriteLine(".NET Framework not defined."); 52 | #endif 53 | 54 | Section(".NET Standard"); 55 | #if NETSTANDARD 56 | Console.WriteLine("NETSTANDARD"); 57 | #endif 58 | #if NETSTANDARD1_0 59 | Console.WriteLine("NETSTANDARD1_0"); 60 | #elif NETSTANDARD1_1 61 | Console.WriteLine("NETSTANDARD1_1"); 62 | #elif NETSTANDARD1_2 63 | Console.WriteLine("NETSTANDARD1_2"); 64 | #elif NETSTANDARD1_3 65 | Console.WriteLine("NETSTANDARD1_3"); 66 | #elif NETSTANDARD1_4 67 | Console.WriteLine("NETSTANDARD1_4"); 68 | #elif NETSTANDARD1_5 69 | Console.WriteLine("NETSTANDARD1_5"); 70 | #elif NETSTANDARD1_6 71 | Console.WriteLine("NETSTANDARD1_6"); 72 | #elif NETSTANDARD2_0 73 | Console.WriteLine("NETSTANDARD2_0"); 74 | #elif NETSTANDARD2_1 75 | Console.WriteLine("NETSTANDARD2_1"); 76 | #else 77 | Console.WriteLine(".NET Standard not defined."); 78 | #endif 79 | 80 | Section(".NET Core"); 81 | #if NETCOREAPP 82 | Console.WriteLine("NETCOREAPP"); 83 | #endif 84 | #if NETCOREAPP1_0 85 | Console.WriteLine("NETCOREAPP1_0"); 86 | #elif NETCOREAPP1_1 87 | Console.WriteLine("NETCOREAPP1_1"); 88 | #elif NETCOREAPP2_0 89 | Console.WriteLine("NETCOREAPP2_0"); 90 | #elif NETCOREAPP2_1 91 | Console.WriteLine("NETCOREAPP2_1"); 92 | #elif NETCOREAPP2_2 93 | Console.WriteLine("NETCOREAPP2_2"); 94 | #elif NETCOREAPP3_0 95 | Console.WriteLine("NETCOREAPP3_0"); 96 | #elif NETCOREAPP3_1 97 | Console.WriteLine("NETCOREAPP3_1"); 98 | #else 99 | Console.WriteLine(".NET Core not defined."); 100 | #endif 101 | 102 | Finish(); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Constants.cs: -------------------------------------------------------------------------------- 1 | namespace CodeSamples 2 | { 3 | public static class Constants 4 | { 5 | public static class Linq 6 | { 7 | public static readonly int MaxSamples = 200; 8 | public static readonly int MinAge = 1; 9 | public static readonly int MaxAge = 40; 10 | } 11 | 12 | public static readonly int SomeConstant = 900; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Enums/EnumSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using CodeSamples.Alterations.Extensions; 4 | 5 | namespace CodeSamples.Enums 6 | { 7 | /// 8 | /// Classic enum 9 | /// 10 | internal enum WeekDay 11 | { 12 | Monday, 13 | Tuesday, 14 | Wednesday, 15 | Thursday, 16 | Friday, 17 | Saturday, 18 | Sunday 19 | } 20 | 21 | /// 22 | /// Classic enum with type and defined values 23 | /// 24 | internal enum Priority : short 25 | { 26 | Lowest = -2, 27 | Low = -1, 28 | Normal = 0, 29 | High = 1, 30 | Highest = 2 31 | } 32 | 33 | /// 34 | /// Flags enum 35 | /// 36 | [Flags] 37 | internal enum SidesAndCorners 38 | { 39 | None = 0, 40 | Top = 1, 41 | Bottom = 2, 42 | Left = 4, 43 | Right = 8, 44 | // 45 | TopLeft = Top | Left, 46 | TopRight = Top | Right, 47 | BottomLeft = Bottom | Left, 48 | BottomRight = Bottom | Right, 49 | // 50 | Full = Top | Bottom | Left | Right 51 | } 52 | 53 | /// 54 | /// Enum with description attribute 55 | /// 56 | internal enum Status 57 | { 58 | [Description("Not Completed")] 59 | NotCompleted, 60 | Completed, 61 | Error 62 | } 63 | 64 | public class EnumSample : SampleExecute 65 | { 66 | private void OutputSidesAndCorners(SidesAndCorners sidesAndCorners) 67 | { 68 | Console.WriteLine($"SidesAndCorners Enum values: default={sidesAndCorners.ToString()}, string={sidesAndCorners.ToString("g")}, flags={sidesAndCorners.ToString("f")}, decimal={sidesAndCorners.ToString("d")}, hex=0x{sidesAndCorners.ToString("x")}"); 69 | } 70 | 71 | public override void Execute() 72 | { 73 | Title("EnumSampleExecute"); 74 | 75 | Section("Simple Enum"); 76 | //'This must be Thursday,' said Arthur to himself, sinking low over his beer. 'I never could get the hang of Thursdays.' 77 | WeekDay weekDay = WeekDay.Thursday; 78 | Console.WriteLine($"weekDay Enum value: default={weekDay.ToString()}, string={weekDay.ToString("g")}, decimal={weekDay.ToString("d")}, hex=0x{weekDay.ToString("x")}"); 79 | var enumValues = Enum.GetNames(typeof(WeekDay)); 80 | Console.WriteLine("WeekDays Enum values:"); 81 | foreach (string value in enumValues) 82 | { 83 | Console.WriteLine(value); 84 | } 85 | LineBreak(); 86 | 87 | Section("Typed Enum (short)"); 88 | Priority priority = Priority.Low; 89 | Console.WriteLine($"Priority Enum values: default={priority.ToString()}, string={priority.ToString("g")}, decimal={priority.ToString("d")}, hex=0x{priority.ToString("x")}"); 90 | priority = Priority.Normal; 91 | Console.WriteLine($"Priority Enum values: default={priority.ToString()}, string={priority.ToString("g")}, decimal={priority.ToString("d")}, hex=0x{priority.ToString("x")}"); 92 | priority = Priority.Highest; 93 | Console.WriteLine($"Priority Enum values: default={priority.ToString()}, string={priority.ToString("g")}, decimal={priority.ToString("d")}, hex=0x{priority.ToString("x")}"); 94 | 95 | 96 | Section("Enum Flags"); 97 | SidesAndCorners sidesAndCorners = SidesAndCorners.Bottom; 98 | OutputSidesAndCorners(sidesAndCorners); 99 | sidesAndCorners = SidesAndCorners.Full; 100 | OutputSidesAndCorners(sidesAndCorners); 101 | sidesAndCorners = SidesAndCorners.Top | SidesAndCorners.Bottom; 102 | OutputSidesAndCorners(sidesAndCorners); 103 | sidesAndCorners = SidesAndCorners.TopLeft; 104 | OutputSidesAndCorners(sidesAndCorners); 105 | 106 | //checking flags 107 | Console.WriteLine($"sidesAndCorners.Top is set={sidesAndCorners.HasFlag(SidesAndCorners.Top)}"); 108 | Console.WriteLine($"sidesAndCorners.TopLeft is set={sidesAndCorners.HasFlag(SidesAndCorners.TopLeft)}"); 109 | Console.WriteLine($"sidesAndCorners.Full is set={sidesAndCorners.HasFlag(SidesAndCorners.Full)}"); 110 | Console.WriteLine($"sidesAndCorners.Bottom is set={sidesAndCorners.HasFlag(SidesAndCorners.Bottom)}"); 111 | 112 | Section("Enum with Description"); 113 | Status status= Status.NotCompleted; 114 | Console.WriteLine($"status value: default={status.ToString()}, string={status.ToString("g")}, decimal={status.ToString("d")}, hex=0x{status.ToString("x")}"); 115 | var statusValues = Enum.GetValues(typeof(Status)); 116 | Console.WriteLine("Status Enum values:"); 117 | foreach (Status value in statusValues) 118 | { 119 | Console.WriteLine($"ordinal={(int)value}, value={value.ToString()}, description={value.GetDescription()}"); 120 | } 121 | LineBreak(); 122 | 123 | Finish(); 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Exceptions/ExceptionsSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Exceptions 4 | { 5 | internal class MyException : Exception 6 | { 7 | public MyException(string message) : base(message) { } 8 | } 9 | 10 | public class ExceptionsSample : SampleExecute 11 | { 12 | public override void Execute() 13 | { 14 | try 15 | { 16 | throw new MyException("My Exception!"); 17 | } 18 | catch (Exception e) 19 | { 20 | Console.WriteLine($"Exception '{e.GetType().Name}' with message '{e.Message}' was thrown."); 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Files/FilesSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Reflection; 4 | 5 | namespace CodeSamples.Files 6 | { 7 | public class FilesSample : SampleExecute 8 | { 9 | private void GetExecutableLocation() 10 | { 11 | var uri = new Uri(Assembly.GetEntryAssembly().GetName().CodeBase); 12 | string location = new FileInfo(uri.AbsolutePath).FullName; 13 | 14 | Console.WriteLine($"Executable Location = {location}"); 15 | } 16 | 17 | private void GetExecutablePath() 18 | { 19 | var uri = Assembly.GetExecutingAssembly().GetName().CodeBase; 20 | string location = Path.GetDirectoryName(uri); 21 | 22 | Console.WriteLine($"Executable Path = {location}"); 23 | } 24 | 25 | private void GetSpecialFolders() 26 | { 27 | Console.WriteLine($"Desktop Location = {Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}"); 28 | 29 | Console.WriteLine($"Application Data Location = {Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}"); 30 | Console.WriteLine($"Local Application Data Location = {Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}"); 31 | 32 | Console.WriteLine($"Common Documents Location = {Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments)}"); 33 | Console.WriteLine($"My Documents Location = {Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)}"); 34 | 35 | Console.WriteLine($"Common Program Files Location = {Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles)}"); 36 | Console.WriteLine($"Common Program Files (x86) Location = {Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFilesX86)}"); 37 | 38 | Console.WriteLine($"Program Files Location = {Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)}"); 39 | Console.WriteLine($"Program Files (x86) Location = {Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)}"); 40 | 41 | Console.WriteLine($"User Profile Location = {Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}"); 42 | Console.WriteLine($"Windows Location = {Environment.GetFolderPath(Environment.SpecialFolder.Windows)}"); 43 | } 44 | 45 | public override void Execute() 46 | { 47 | Title("FilesSampleExecute"); 48 | 49 | GetExecutableLocation(); 50 | GetExecutablePath(); 51 | GetSpecialFolders(); 52 | 53 | Finish(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/ISampleExecute.cs: -------------------------------------------------------------------------------- 1 | namespace CodeSamples 2 | { 3 | public interface ISampleExecute 4 | { 5 | void Execute(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/MultiThreading/BackgroundWorkerSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.Threading; 4 | 5 | namespace CodeSamples.MultiThreading 6 | { 7 | public class BackgroundWorkerSample 8 | { 9 | private readonly AutoResetEvent resetEvent = new AutoResetEvent(false); 10 | 11 | public void Go() 12 | { 13 | BackgroundWorker backgroundWorker = new BackgroundWorker(); 14 | backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundWorker_DoWork); 15 | backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted); 16 | backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged); 17 | backgroundWorker.WorkerReportsProgress = true; 18 | backgroundWorker.WorkerSupportsCancellation = true; 19 | //start background worker 20 | if(!backgroundWorker.IsBusy) 21 | { 22 | backgroundWorker.RunWorkerAsync(); 23 | } 24 | //wait for background worker to finish; not necessary, but required for testing samples, so they execute in order 25 | resetEvent.WaitOne(); 26 | } 27 | 28 | private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) 29 | { 30 | Console.WriteLine($"...reporting progress: {e.ProgressPercentage}%"); 31 | } 32 | 33 | private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) 34 | { 35 | BackgroundWorker worker = (BackgroundWorker)sender; 36 | for(int i=0;i<11;i++) 37 | { 38 | Console.WriteLine($"...doing it's job"); 39 | worker.ReportProgress(i*10); 40 | System.Threading.Thread.Sleep(50); 41 | } 42 | e.Result = 42; //object, can use any class 43 | } 44 | 45 | private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 46 | { 47 | Console.WriteLine($"...done, Result = {e.Result.ToString()}"); 48 | resetEvent.Set(); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/MultiThreading/MultithreadingSample.cs: -------------------------------------------------------------------------------- 1 | namespace CodeSamples.MultiThreading 2 | { 3 | public class MultithreadingSample : SampleExecute 4 | { 5 | public override void Execute() 6 | { 7 | Title("MultithreadingSample"); 8 | 9 | Section("BackgroundWorker is online..."); 10 | var backgroundWorkerSample = new BackgroundWorkerSample(); 11 | backgroundWorkerSample.Go(); 12 | 13 | LineBreak(); 14 | 15 | Section("Thread is online..."); 16 | var threadSample = new ThreadSample(); 17 | threadSample.Go(); 18 | 19 | Finish(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/MultiThreading/ThreadSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | 4 | namespace CodeSamples.MultiThreading 5 | { 6 | internal class LaborInstructions 7 | { 8 | private readonly AutoResetEvent _syncObject; 9 | 10 | public string SomeParameter { get; set; } 11 | 12 | public AutoResetEvent SyncObject => _syncObject; 13 | 14 | public LaborInstructions(AutoResetEvent syncObject) 15 | { 16 | _syncObject = syncObject; 17 | } 18 | } 19 | 20 | internal class ThreadLabor 21 | { 22 | public void DoWork(object instructions) 23 | { 24 | var passedParametersClass = instructions as LaborInstructions; 25 | Console.WriteLine($"Doing labor... {passedParametersClass.SomeParameter} ... and waiting to complete..."); 26 | Thread.Sleep(1000); 27 | passedParametersClass.SyncObject.Set(); 28 | } 29 | } 30 | 31 | public class ThreadSample 32 | { 33 | private readonly AutoResetEvent syncObject = new AutoResetEvent(false); 34 | 35 | public void Go() 36 | { 37 | var threadLabor = new ThreadLabor(); 38 | var laborInstructions = new LaborInstructions(syncObject) 39 | { 40 | SomeParameter = $"Current DateTime is {DateTime.Now.ToString()}" 41 | }; 42 | 43 | Console.WriteLine("Going into thread..."); 44 | var thread = new Thread(threadLabor.DoWork) 45 | { 46 | Priority = ThreadPriority.Highest 47 | }; 48 | thread.Start(laborInstructions); 49 | syncObject.WaitOne(); 50 | Console.WriteLine("done!"); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/Behavioral/ChainOfResponsibilityPattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace CodeSamples.Patterns.Behavioral 8 | { 9 | public class ChainOfResponsibilityPatternSample : SampleExecute 10 | { 11 | internal abstract class Handler 12 | { 13 | protected Handler Successor { get; private set; } 14 | 15 | public void SetSuccessor(Handler successor) 16 | { 17 | this.Successor = successor; 18 | } 19 | 20 | public abstract void HandleRequest(string deviceName, int request); 21 | } 22 | 23 | internal class HandlerDeviceKeyboard : Handler 24 | { 25 | public override void HandleRequest(string deviceName, int request) 26 | { 27 | if (deviceName.Equals("keyboard", StringComparison.OrdinalIgnoreCase)) 28 | { 29 | Console.WriteLine($"Handled Request {request} for device {deviceName} by {this.GetType().Name}"); 30 | } 31 | else Successor?.HandleRequest(deviceName, request); 32 | } 33 | } 34 | 35 | internal class HandlerDeviceMouse : Handler 36 | { 37 | public override void HandleRequest(string deviceName, int request) 38 | { 39 | if (deviceName.Equals("mouse", StringComparison.OrdinalIgnoreCase)) 40 | { 41 | Console.WriteLine($"Handled Request {request} for device {deviceName} by {this.GetType().Name}"); 42 | } 43 | else Successor?.HandleRequest(deviceName, request); 44 | } 45 | } 46 | 47 | internal class HandlerDeviceNetwork : Handler 48 | { 49 | public override void HandleRequest(string deviceName, int request) 50 | { 51 | if (deviceName.Equals("network", StringComparison.OrdinalIgnoreCase)) 52 | { 53 | Console.WriteLine($"Handled Request {request} for device {deviceName} by {this.GetType().Name}"); 54 | } 55 | else Successor?.HandleRequest(deviceName, request); 56 | } 57 | } 58 | 59 | public override void Execute() 60 | { 61 | Section("Chain of Responsibility Pattern"); 62 | var keyboard = new HandlerDeviceKeyboard(); 63 | var mouse = new HandlerDeviceMouse(); 64 | var network = new HandlerDeviceNetwork(); 65 | 66 | keyboard.SetSuccessor(mouse); 67 | mouse.SetSuccessor(network); 68 | 69 | keyboard.HandleRequest("mouse", 10); 70 | keyboard.HandleRequest("network", 12); 71 | keyboard.HandleRequest("keyboard", 102); 72 | keyboard.HandleRequest("something", 11); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/Behavioral/ObserverPattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace CodeSamples.Patterns.Behavioral 5 | { 6 | #region Observable classes and interfaces 7 | 8 | //Also ISubject 9 | interface IObservable 10 | { 11 | bool Attach(IObserver observer); 12 | bool Detach(IObserver observer); 13 | void Notify(); 14 | //used, when higher abstraction is used (class ConcreteObserverAbstract) 15 | int GetValueForAbstract(); 16 | } 17 | 18 | interface IObserver 19 | { 20 | void Update(); 21 | void UpdateWithObservableParam(IObservable observable); 22 | void UpdateWithResultParam(ValuesClass values); 23 | } 24 | 25 | class ValuesClass 26 | { 27 | public int Value { get; set; } = 12; 28 | } 29 | 30 | class ConcreteObservable : IObservable 31 | { 32 | private List _observers = new List(); 33 | 34 | public bool Attach(IObserver observer) 35 | { 36 | _observers.Add(observer); 37 | return true; 38 | } 39 | 40 | public bool Detach(IObserver observer) 41 | { 42 | _observers.Remove(observer); 43 | return true; 44 | } 45 | 46 | public int GetValueForAbstract() 47 | { 48 | return 5; 49 | } 50 | 51 | public int GetValueForClass() 52 | { 53 | return 3; 54 | } 55 | 56 | public void Notify() 57 | { 58 | foreach (IObserver observer in _observers) 59 | { 60 | observer.Update(); 61 | observer.UpdateWithObservableParam(this); 62 | observer.UpdateWithResultParam(new ValuesClass()); 63 | } 64 | } 65 | } 66 | 67 | class ConcreteObserverAbstract : IObserver 68 | { 69 | readonly IObservable _observable = null; 70 | 71 | public ConcreteObserverAbstract(IObservable observable) 72 | { 73 | _observable = observable; 74 | _observable.Attach(this); 75 | } 76 | 77 | public void Update() 78 | { 79 | Console.WriteLine($"Abstract Update w/o params: {_observable.GetValueForAbstract()}"); 80 | } 81 | 82 | public void UpdateWithObservableParam(IObservable observable) 83 | { 84 | Console.WriteLine($"Abstract Update with IObservable parameter: {observable.GetValueForAbstract()}"); 85 | } 86 | 87 | public void UpdateWithResultParam(ValuesClass values) 88 | { 89 | Console.WriteLine($"Abstract Update with ValuesClass parameter: {values.Value}"); 90 | } 91 | } 92 | 93 | //ConcreteObserver vs. ConcreteObserverAbstract: 94 | // ConcreteObserver has a class as parameter in constructor, so any mesthod, not defined in interface can be called 95 | // ConcreteObserverAbstract has an interface, so only methods in interface can be called 96 | class ConcreteObserver : IObserver 97 | { 98 | ConcreteObservable _observable = null; 99 | 100 | public ConcreteObserver(ConcreteObservable observable) 101 | { 102 | _observable = observable; 103 | _observable.Attach(this); 104 | } 105 | 106 | public void Update() 107 | { 108 | Console.WriteLine($"Update w/o params: {_observable.GetValueForAbstract()}, Concrete: {_observable.GetValueForClass()}"); 109 | } 110 | 111 | public void UpdateWithObservableParam(IObservable observable) 112 | { 113 | Console.WriteLine($"Update with IObservable parameter: {observable.GetValueForAbstract()}"); 114 | } 115 | 116 | public void UpdateWithResultParam(ValuesClass values) 117 | { 118 | Console.WriteLine($"Update with ValuesClass parameter: {values.Value}"); 119 | } 120 | } 121 | #endregion 122 | 123 | public class ObserverPatternSample : SampleExecute 124 | { 125 | public override void Execute() 126 | { 127 | Section("Observer Pattern"); 128 | var observable = new ConcreteObservable(); 129 | var concreteObserver = new ConcreteObserver(observable); 130 | var concreteObserverAbstract = new ConcreteObserverAbstract(observable); 131 | observable.Notify(); //Notify() is usually called from inside the class, when and where the change happens... 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/Behavioral/StatePattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Patterns.Behavioral 4 | { 5 | #region Abstract Pattern classes and interfaces 6 | abstract class State 7 | { 8 | public abstract void Handle(Context context); 9 | } 10 | 11 | class ConcreteStateRead : State 12 | { 13 | public override void Handle(Context context) 14 | { 15 | Console.WriteLine("...reading"); 16 | context.State = new ConcreteStateWrite(); 17 | } 18 | } 19 | 20 | class ConcreteStateWrite : State 21 | { 22 | public override void Handle(Context context) 23 | { 24 | Console.WriteLine("...writing"); 25 | context.State = new ConcreteStateWait(); 26 | } 27 | } 28 | 29 | class ConcreteStateWait : State 30 | { 31 | public override void Handle(Context context) 32 | { 33 | Console.WriteLine("...waiting"); 34 | context.State = new ConcreteStateRead(); 35 | } 36 | } 37 | 38 | class Context 39 | { 40 | private State _state; 41 | 42 | public Context(State state) 43 | { 44 | _state = state; 45 | } 46 | 47 | public State State 48 | { 49 | get => _state; 50 | set 51 | { 52 | _state = value; 53 | Console.WriteLine($"New state: {_state.GetType().Name}"); 54 | } 55 | } 56 | 57 | public void Request() 58 | { 59 | _state.Handle(this); 60 | } 61 | } 62 | #endregion 63 | 64 | public class StatePatternSample : SampleExecute 65 | { 66 | public override void Execute() 67 | { 68 | Section("State Pattern"); 69 | var state = new Context(new ConcreteStateRead()); 70 | state.Request(); 71 | state.Request(); 72 | state.Request(); 73 | state.Request(); 74 | state.Request(); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/Behavioral/StrategyPattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace CodeSamples.Patterns.Behavioral 5 | { 6 | #region Strategy classes and interfaces 7 | interface ISortStrategy 8 | { 9 | void Sort(List sortableList); 10 | } 11 | 12 | class QuickSortStrategy : ISortStrategy 13 | { 14 | public void Sort(List sortableList) 15 | { 16 | Console.WriteLine($"Quick Sort Called..."); 17 | } 18 | } 19 | 20 | class ShellSortStrategy : ISortStrategy 21 | { 22 | public void Sort(List sortableList) 23 | { 24 | Console.WriteLine($"Shell Sort Called..."); 25 | } 26 | } 27 | 28 | class InsertionSortStrategy : ISortStrategy 29 | { 30 | public void Sort(List sortableList) 31 | { 32 | Console.WriteLine($"Insertion Sort Called..."); 33 | } 34 | } 35 | #endregion 36 | 37 | class StrategyTestClass 38 | { 39 | private ISortStrategy _sortStrategy = null; 40 | private readonly List _sortableList = new List() { 5, 3, 7, 12, 100, 1 }; 41 | 42 | public void SetSortStrategy(ISortStrategy sortStrategy) 43 | { 44 | _sortStrategy = sortStrategy; 45 | } 46 | 47 | public void Sort() 48 | { 49 | _sortStrategy.Sort(_sortableList); 50 | } 51 | } 52 | 53 | public class StrategyPatternSample : SampleExecute 54 | { 55 | public override void Execute() 56 | { 57 | Section("Strategy Pattern"); 58 | var testClass = new StrategyTestClass(); 59 | testClass.SetSortStrategy(new QuickSortStrategy()); 60 | testClass.Sort(); 61 | testClass.SetSortStrategy(new ShellSortStrategy()); 62 | testClass.Sort(); 63 | testClass.SetSortStrategy(new InsertionSortStrategy()); 64 | testClass.Sort(); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/Creational/AbstractFactoryPattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace CodeSamples.Patterns.Creational 8 | { 9 | #region Abstract Factory Pattern Classes and Interfaces 10 | interface IElement 11 | { 12 | void Paint(); 13 | } 14 | 15 | interface IGuiFactory 16 | { 17 | IElement CreateElement(); 18 | } 19 | 20 | #region Windows 21 | class WindowsElement : IElement 22 | { 23 | public void Paint() 24 | { 25 | Console.WriteLine($"WindowsElement Paint"); 26 | } 27 | } 28 | 29 | class WindowsGuiFactory : IGuiFactory 30 | { 31 | public IElement CreateElement() 32 | { 33 | return new WindowsElement(); 34 | } 35 | } 36 | #endregion 37 | 38 | #region Linux 39 | class LinuxElement : IElement 40 | { 41 | public void Paint() 42 | { 43 | Console.WriteLine($"LinuxElement Paint"); 44 | } 45 | } 46 | 47 | class LinuxGuiFactory : IGuiFactory 48 | { 49 | public IElement CreateElement() 50 | { 51 | return new LinuxElement(); 52 | } 53 | } 54 | #endregion 55 | 56 | #region OsX 57 | class MacOsXElement : IElement 58 | { 59 | public void Paint() 60 | { 61 | Console.WriteLine($"MacOsXElement Paint"); 62 | } 63 | } 64 | 65 | class MacOsXGuiFactory : IGuiFactory 66 | { 67 | public IElement CreateElement() 68 | { 69 | return new MacOsXElement(); 70 | } 71 | } 72 | #endregion 73 | 74 | #endregion 75 | 76 | public class AbstractFactoryPatternSample : SampleExecute 77 | { 78 | public override void Execute() 79 | { 80 | Section("Abstract Factory Pattern"); 81 | IGuiFactory guiFactory = new WindowsGuiFactory(); 82 | var element = guiFactory.CreateElement(); 83 | element.Paint(); 84 | // 85 | guiFactory = new LinuxGuiFactory(); 86 | element = guiFactory.CreateElement(); 87 | element.Paint(); 88 | // 89 | guiFactory = new MacOsXGuiFactory(); 90 | element = guiFactory.CreateElement(); 91 | element.Paint(); 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/Creational/FactoryMethodPattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace CodeSamples.Patterns.Creational 5 | { 6 | #region Factory Method Pattern Classes and Interfaces 7 | abstract class VeganStuff { } 8 | class Bread : VeganStuff { } 9 | class Cheese : VeganStuff { } 10 | class Tomato : VeganStuff { } 11 | class Lettuce : VeganStuff { } 12 | class Mayonnaise : VeganStuff { } 13 | 14 | abstract class Sandwich 15 | { 16 | public Sandwich() 17 | { 18 | MakeSandwich(); 19 | } 20 | 21 | //Factory Method 22 | public abstract void MakeSandwich(); 23 | 24 | public List Ingredients { get; } = new List(); 25 | 26 | public void ListIngredients() 27 | { 28 | foreach(var ingredient in Ingredients) 29 | { 30 | Console.WriteLine($" ingredient = {ingredient.GetType().Name}"); 31 | } 32 | } 33 | } 34 | 35 | class VeggieSandwich : Sandwich 36 | { 37 | public override void MakeSandwich() 38 | { 39 | Ingredients.Add(new Bread()); 40 | Ingredients.Add(new Lettuce()); 41 | Ingredients.Add(new Tomato()); 42 | Ingredients.Add(new Cheese()); 43 | Ingredients.Add(new Mayonnaise()); 44 | Ingredients.Add(new Bread()); 45 | } 46 | } 47 | 48 | class TomatoSandwich : Sandwich 49 | { 50 | public override void MakeSandwich() 51 | { 52 | Ingredients.Add(new Bread()); 53 | Ingredients.Add(new Tomato()); 54 | Ingredients.Add(new Bread()); 55 | } 56 | } 57 | #endregion 58 | 59 | public class FactoryMethodPatternSample : SampleExecute 60 | { 61 | public override void Execute() 62 | { 63 | Section("Factory Method Pattern"); 64 | Section("Veggie Sandwich"); 65 | var veggieSandwich = new VeggieSandwich(); 66 | veggieSandwich.ListIngredients(); 67 | Section("Tomato Sandwich"); 68 | var tomatoSandwich = new TomatoSandwich(); 69 | tomatoSandwich.ListIngredients(); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/Creational/SingletonPattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Patterns.Creational 4 | { 5 | public class SingletonPattern 6 | { 7 | #region Singleton 8 | static readonly SingletonPattern _instance = new SingletonPattern(); 9 | public static SingletonPattern Instance { get { return _instance; } } 10 | #endregion 11 | 12 | public void SomeMethod() 13 | { 14 | Console.WriteLine("Singleton method called"); 15 | } 16 | 17 | public void SomeOtherMethod() 18 | { 19 | Console.WriteLine("Singleton other method called"); 20 | } 21 | } 22 | 23 | public class SingletonPatternSample : SampleExecute 24 | { 25 | public override void Execute() 26 | { 27 | Section("Singleton Pattern"); 28 | SingletonPattern.Instance.SomeMethod(); 29 | SingletonPattern.Instance.SomeOtherMethod(); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/Other/RepositoryPattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Linq; 5 | using System.Linq.Expressions; 6 | 7 | namespace CodeSamples.Patterns.Other 8 | { 9 | #region Repository Pattern Classes and Interfaces 10 | interface IEntity 11 | { 12 | int Id { get; set; } 13 | } 14 | 15 | //can be solved with interface... 16 | interface IRepository where T : IEntity 17 | { 18 | T GetById(int id); 19 | IEnumerable GetAll(); 20 | IEnumerable Find(Expression> predicate); 21 | void Add(T entity); 22 | void Remove(T entity); 23 | } 24 | 25 | //...or obstract class 26 | class RepositoryAbstract where T : IEntity 27 | { 28 | private readonly Collection _entityRepository; 29 | 30 | public RepositoryAbstract(Collection dbContext) 31 | { 32 | _entityRepository = dbContext; 33 | } 34 | 35 | public RepositoryAbstract() : this(new Collection()) { } 36 | 37 | public T GetById(int id) 38 | { 39 | var result = _entityRepository.FirstOrDefault(o => o.Id == id); 40 | return result; 41 | } 42 | 43 | public IEnumerable List() 44 | { 45 | return _entityRepository; 46 | } 47 | 48 | public IEnumerable List(Expression> predicate) 49 | { 50 | return _entityRepository.AsQueryable().Where(predicate).OrderBy(o => o.Id); 51 | } 52 | 53 | public void Add(T entity) 54 | { 55 | _entityRepository.Add(entity); 56 | } 57 | 58 | public void Delete(T entity) 59 | { 60 | _entityRepository.Remove(entity); 61 | } 62 | } 63 | 64 | class Entity : IEntity 65 | { 66 | public int Id { get; set; } 67 | public string Name { get; set; } 68 | } 69 | 70 | class EntityRepository : IRepository 71 | { 72 | //_entityRepository is Database Context for this case 73 | private readonly Collection _entityRepository = new Collection(); 74 | 75 | public void Add(Entity entity) 76 | { 77 | _entityRepository.Add(entity); 78 | //_entityRepository.SaveChanges(); 79 | } 80 | 81 | public void Remove(Entity entity) 82 | { 83 | _entityRepository.Remove(entity); 84 | } 85 | 86 | public Entity GetById(int id) 87 | { 88 | var result = _entityRepository.FirstOrDefault(o => o.Id == id); 89 | return result; 90 | } 91 | 92 | public IEnumerable GetAll() 93 | { 94 | return _entityRepository; 95 | } 96 | 97 | public IEnumerable Find(Expression> predicate) 98 | { 99 | return _entityRepository.AsQueryable().Where(predicate).OrderBy(o => o.Id); 100 | } 101 | } 102 | #endregion 103 | 104 | public class SingletonPatternSample : SampleExecute 105 | { 106 | public override void Execute() 107 | { 108 | var repository = new EntityRepository(); 109 | repository.Add(new Entity() { Id = 1 }); 110 | var result = repository.Find(o => o.Id > 10); 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/Other/UnitOfWorkPattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Patterns.Other 4 | { 5 | class Person : IEntity 6 | { 7 | public int Id { get; set; } 8 | public string Name { get; set; } 9 | } 10 | 11 | class Address : IEntity 12 | { 13 | public int Id { get; set; } 14 | public string Street { get; set; } 15 | } 16 | 17 | interface IUnitOfWork 18 | { 19 | IRepository PersonRepository { get; } 20 | IRepository
AddressRepository { get; } 21 | void Complete(); 22 | } 23 | 24 | class UnitOfWork : IUnitOfWork 25 | { 26 | public IRepository PersonRepository => throw new NotImplementedException(); 27 | 28 | public IRepository
AddressRepository => throw new NotImplementedException(); 29 | 30 | public void Complete() 31 | { 32 | throw new NotImplementedException(); 33 | } 34 | } 35 | 36 | public class UnitOfWorkPattern : SampleExecute 37 | { 38 | public override void Execute() 39 | { 40 | throw new NotImplementedException(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/PatternsSample.cs: -------------------------------------------------------------------------------- 1 | using CodeSamples.Patterns.Behavioral; 2 | using CodeSamples.Patterns.Creational; 3 | using CodeSamples.Patterns.Structural; 4 | 5 | namespace CodeSamples.Patterns 6 | { 7 | public class PatternsSample : SampleExecute 8 | { 9 | public override void Execute() 10 | { 11 | Title("PatternsSampleExecute"); 12 | 13 | Section("Creational Patterns"); 14 | var singleton = new SingletonPatternSample(); 15 | singleton.Execute(); 16 | var factoryMethod = new FactoryMethodPatternSample(); 17 | factoryMethod.Execute(); 18 | var abstractFactory = new AbstractFactoryPatternSample(); 19 | abstractFactory.Execute(); 20 | LineBreak(); 21 | 22 | Section("Behavioral Patterns"); 23 | var strategy = new StrategyPatternSample(); 24 | strategy.Execute(); 25 | var observer = new ObserverPatternSample(); 26 | observer.Execute(); 27 | var state = new StatePatternSample(); 28 | state.Execute(); 29 | var chainOfResponsibility = new ChainOfResponsibilityPatternSample(); 30 | chainOfResponsibility.Execute(); 31 | LineBreak(); 32 | 33 | Section("Structural Patterns"); 34 | var decorator = new DecoratorPatternSample(); 35 | decorator.Execute(); 36 | var facade = new FacadePatternSample(); 37 | facade.Execute(); 38 | 39 | Finish(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/Structural/DecoratorPattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Patterns.Structural 4 | { 5 | public class DecoratorPatternSample : SampleExecute 6 | { 7 | 8 | internal interface IBird 9 | { 10 | string Fly(); 11 | } 12 | 13 | internal class Bird : IBird 14 | { 15 | public string Fly() 16 | { 17 | return "Flying"; 18 | } 19 | } 20 | 21 | //decorator classes 22 | internal class FasterBird : IBird 23 | { 24 | protected readonly IBird _bird; 25 | 26 | public FasterBird(IBird bird) 27 | { 28 | _bird = bird; 29 | } 30 | 31 | public string Fly() 32 | { 33 | return $"{_bird.Fly()} faster"; 34 | } 35 | } 36 | 37 | internal class FastestBird : IBird 38 | { 39 | protected readonly IBird _bird; 40 | 41 | public FastestBird(IBird bird) 42 | { 43 | _bird = bird; 44 | } 45 | 46 | public string Fly() 47 | { 48 | return $"{_bird.Fly()} like tail is on fire"; 49 | } 50 | } 51 | 52 | public override void Execute() 53 | { 54 | Section("Decorator Pattern"); 55 | var bird = new Bird(); 56 | Console.WriteLine(bird.Fly()); 57 | 58 | var fasterBird = new FasterBird(bird); 59 | Console.WriteLine(fasterBird.Fly()); 60 | 61 | var fastestBird = new FastestBird(fasterBird); 62 | Console.WriteLine(fastestBird.Fly()); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Patterns/Structural/FacadePattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Patterns.Structural 4 | { 5 | public class FacadePatternSample : SampleExecute 6 | { 7 | 8 | internal class SubSystemOne 9 | { 10 | public void DoSomething() 11 | { 12 | Console.WriteLine("Doing Something"); 13 | } 14 | } 15 | 16 | internal class SubSystemTwo 17 | { 18 | public void DoSomethingElse() 19 | { 20 | Console.WriteLine("Doing Something Else"); 21 | } 22 | } 23 | 24 | internal class SubSystemThree 25 | { 26 | public void WriteABook() 27 | { 28 | Console.WriteLine("Writing a book"); 29 | } 30 | } 31 | 32 | internal class SubSystemFour 33 | { 34 | public void Swim() 35 | { 36 | Console.WriteLine("Swimming"); 37 | } 38 | } 39 | 40 | internal class FacadeClass 41 | { 42 | private readonly SubSystemOne _one = new SubSystemOne(); 43 | private readonly SubSystemTwo _two = new SubSystemTwo(); 44 | private readonly SubSystemThree _three = new SubSystemThree(); 45 | private readonly SubSystemFour _four = new SubSystemFour(); 46 | 47 | public void GoLeisureTimeMethodOne() 48 | { 49 | _one.DoSomething(); 50 | _three.WriteABook(); 51 | _four.Swim(); 52 | } 53 | 54 | public void GoLeisureTimeAll() 55 | { 56 | _one.DoSomething(); 57 | _two.DoSomethingElse(); 58 | _three.WriteABook(); 59 | _four.Swim(); 60 | } 61 | } 62 | 63 | public override void Execute() 64 | { 65 | Section("Facade Pattern"); 66 | var facade = new FacadeClass(); 67 | 68 | facade.GoLeisureTimeMethodOne(); 69 | Console.WriteLine(); 70 | facade.GoLeisureTimeAll(); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Program.cs: -------------------------------------------------------------------------------- 1 | using CodeSamples.Alterations; 2 | using CodeSamples.Attributes; 3 | using CodeSamples.Classes; 4 | using CodeSamples.Comparing; 5 | using CodeSamples.ConditionalDefines; 6 | using CodeSamples.Enums; 7 | using CodeSamples.Exceptions; 8 | using CodeSamples.Files; 9 | using CodeSamples.MultiThreading; 10 | using CodeSamples.Patterns; 11 | using CodeSamples.RegularExpressions; 12 | using CodeSamples.Settings; 13 | using CodeSamples.SOLID.S01_SingleResponsibilityPrinciple_SRP; 14 | using CodeSamples.SOLID.S04_InversionOfControl_IoC; 15 | using CodeSamples.Structures; 16 | using CodeSamples.SyntacticSugars; 17 | using CodeSamples.Timing; 18 | using CodeSamples.TupleDeconstruction; 19 | using CodeSamples.Useful; 20 | using CodeSamples.UsefulClasses; 21 | using System; 22 | 23 | namespace CodeSamples 24 | { 25 | static class Program 26 | { 27 | static void Main(string[] args) 28 | { 29 | Console.Title = "C# Code Samples"; 30 | Console.OutputEncoding = System.Text.Encoding.UTF8; 31 | 32 | Console.WriteLine("Start Code Samples"); 33 | Console.WriteLine(); 34 | 35 | #region Tuple Deconstruction 36 | var tupleDecon = new TupleDeconstructionSample(); 37 | tupleDecon.Execute(); 38 | #endregion 39 | 40 | #region Dictionaries 41 | var dics = new DictionariesSample(); 42 | dics.Execute(); 43 | #endregion 44 | 45 | #region Object Pool 46 | var objectPool = new ObjectPoolSample(); 47 | objectPool.Execute(); 48 | #endregion 49 | 50 | #region Syntactic Sugars 51 | var props = new PropertiesSample(); 52 | props.Execute(); 53 | 54 | var Sample = new UsingSample(); 55 | Sample.Execute(); 56 | 57 | var stringInterpolation = new StringInterpolationSample(); 58 | stringInterpolation.Execute(); 59 | 60 | var patternMatchingSample = new PatternMatchingSample(); 61 | patternMatchingSample.Execute(); 62 | 63 | var nullSample = new NullSample(); 64 | nullSample.Execute(); 65 | #endregion 66 | 67 | #region Useful 68 | var classAndMethodNamesSample = new ClassAndMethodNamesSample(); 69 | classAndMethodNamesSample.Execute(); 70 | 71 | var callerInfo = new CallerInfoSample(); 72 | callerInfo.Execute(); 73 | #endregion 74 | 75 | #region Patterns 76 | var patternsSample = new PatternsSample(); 77 | patternsSample.Execute(); 78 | #endregion 79 | 80 | #region LINQ 81 | var linqSample = new LinqSample(); 82 | linqSample.Execute(); 83 | #endregion 84 | 85 | #region Operators 86 | var operatorOverloadingSample = new OperatorOverloadingSample(); 87 | operatorOverloadingSample.Execute(); 88 | #endregion 89 | 90 | #region Entity Conversion 91 | var entityConversionSample = new EntityConversionSample(); 92 | entityConversionSample.Execute(); 93 | #endregion 94 | 95 | #region Classes 96 | var constructorChainingSample = new ConstructorChainingSample(); 97 | constructorChainingSample.Execute(); 98 | 99 | var anonymousTypesSample = new AnonymousTypesSample(); 100 | anonymousTypesSample.Execute(); 101 | #endregion 102 | 103 | #region Attributes 104 | var debuggerAttributeSample = new DebuggingSample(); 105 | debuggerAttributeSample.Execute(); 106 | 107 | var obsoleteAttributeSample = new ObsoleteSample(); 108 | obsoleteAttributeSample.Execute(); 109 | 110 | var conditionalAttributeSample = new ConditionalSample(); 111 | conditionalAttributeSample.Execute(); 112 | #endregion 113 | 114 | #region Threading 115 | var multithreadingSample = new MultithreadingSample(); 116 | multithreadingSample.Execute(); 117 | #endregion 118 | 119 | #region Equality 120 | var compareSample = new CompareSample(); 121 | compareSample.Execute(); 122 | #endregion 123 | 124 | #region SOLID 125 | var solidSrp = new SingleResponsibilityPrincipleSample(); 126 | solidSrp.Execute(); 127 | 128 | var solidIoC = new InversionOfControlSample(); 129 | solidIoC.Execute(); 130 | #endregion 131 | 132 | #region Timing 133 | var timingSample = new TimingSample(); 134 | timingSample.Execute(); 135 | #endregion 136 | 137 | #region Garbage Collection 138 | var gcSample = new GarbageCollectionSample(); 139 | gcSample.Execute(); 140 | #endregion 141 | 142 | #region Class Extensions 143 | var classExtensionSample = new ClassExtensionSample(); 144 | classExtensionSample.Execute(); 145 | #endregion 146 | 147 | #region Conditional defines 148 | var conditionalDefinesSample = new ConditionalDefinesSample(); 149 | conditionalDefinesSample.Execute(); 150 | #endregion 151 | 152 | #region Enums 153 | var enumSample = new EnumSample(); 154 | enumSample.Execute(); 155 | #endregion 156 | 157 | #region Arithmetic Overflow 158 | var overflowCheckSample = new OverflowCheckSample(); 159 | overflowCheckSample.Execute(); 160 | #endregion 161 | 162 | #region Generics 163 | var genericsSample = new GenericsSample(); 164 | genericsSample.Execute(); 165 | #endregion 166 | 167 | #region Exceptions 168 | var exceptionsSample = new ExceptionsSample(); 169 | exceptionsSample.Execute(); 170 | #endregion 171 | 172 | #region Settings 173 | var settingsSample = new SettingsSample(); 174 | settingsSample.Execute(); 175 | #endregion 176 | 177 | #region Files 178 | var filesSample = new FilesSample(); 179 | filesSample.Execute(); 180 | #endregion 181 | 182 | #region Struct 183 | var structSample = new StructSample(); 184 | structSample.Execute(); 185 | #endregion 186 | 187 | #region Static Classes 188 | var staticSample = new StaticSample(); 189 | staticSample.Execute(); 190 | #endregion 191 | 192 | #region Collection Initializers 193 | var collectionInitializerSamples = new CollectionInitializerSamples(); 194 | collectionInitializerSamples.Execute(); 195 | #endregion 196 | 197 | #region [Regular Expressions] 198 | var regularExpressionSample = new RegExSample(); 199 | regularExpressionSample.Execute(); 200 | #endregion 201 | 202 | #region [Result] 203 | var resultSample = new ResultSample(); 204 | resultSample.Execute(); 205 | #endregion 206 | 207 | Console.WriteLine(); 208 | Console.WriteLine("End Code Samples"); 209 | 210 | Console.ReadKey(); 211 | } 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CodeSamples")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CodeSamples")] 13 | [assembly: AssemblyCopyright("Copyright © 2019")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("8299a09c-bcd3-4018-b0cc-853d8557e965")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Properties/OtherSettings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace CodeSamples.Properties { 12 | 13 | 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.0.0")] 16 | internal sealed partial class OtherSettings : global::System.Configuration.ApplicationSettingsBase { 17 | 18 | private static OtherSettings defaultInstance = ((OtherSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new OtherSettings()))); 19 | 20 | public static OtherSettings Default { 21 | get { 22 | return defaultInstance; 23 | } 24 | } 25 | 26 | [global::System.Configuration.UserScopedSettingAttribute()] 27 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 28 | [global::System.Configuration.DefaultSettingValueAttribute("")] 29 | public string SomeOtherStringSetting { 30 | get { 31 | return ((string)(this["SomeOtherStringSetting"])); 32 | } 33 | set { 34 | this["SomeOtherStringSetting"] = value; 35 | } 36 | } 37 | 38 | [global::System.Configuration.UserScopedSettingAttribute()] 39 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 40 | [global::System.Configuration.DefaultSettingValueAttribute("0")] 41 | public int SomeOtherIntSetting { 42 | get { 43 | return ((int)(this["SomeOtherIntSetting"])); 44 | } 45 | set { 46 | this["SomeOtherIntSetting"] = value; 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Properties/OtherSettings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 10 | 11 | 12 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace CodeSamples.Properties { 12 | 13 | 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.0.0")] 16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { 17 | 18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 19 | 20 | public static Settings Default { 21 | get { 22 | return defaultInstance; 23 | } 24 | } 25 | 26 | [global::System.Configuration.UserScopedSettingAttribute()] 27 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 28 | [global::System.Configuration.DefaultSettingValueAttribute("StringValue")] 29 | public string SettingString { 30 | get { 31 | return ((string)(this["SettingString"])); 32 | } 33 | set { 34 | this["SettingString"] = value; 35 | } 36 | } 37 | 38 | [global::System.Configuration.UserScopedSettingAttribute()] 39 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 40 | [global::System.Configuration.DefaultSettingValueAttribute("0")] 41 | public int SettingInt { 42 | get { 43 | return ((int)(this["SettingInt"])); 44 | } 45 | set { 46 | this["SettingInt"] = value; 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | StringValue 7 | 8 | 9 | 0 10 | 11 | 12 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/RegularExpressions/RegExSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.RegularExpressions; 3 | 4 | namespace CodeSamples.RegularExpressions 5 | { 6 | public class RegExSample : SampleExecute 7 | { 8 | private void IsMatchSnipet() 9 | { 10 | string pattern = @"^This sentence"; 11 | string sentenceYes = $"This sentence is a match."; 12 | string sentenceNo = $"This weird sentence is not a match."; 13 | 14 | Console.WriteLine($"The sentence '{sentenceYes}' is {(Regex.IsMatch(sentenceYes, pattern) ? "" : "not")} a match to pattern '{pattern}'"); 15 | Console.WriteLine($"The sentence '{sentenceNo}' is {(Regex.IsMatch(sentenceNo, pattern) ? "" : "not")} a match to pattern '{pattern}'"); 16 | } 17 | 18 | public override void Execute() 19 | { 20 | Title("RegExSampleExecute"); 21 | 22 | IsMatchSnipet(); 23 | 24 | Finish(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SOLID/S01-SingleResponsibilityPrinciple_SRP/GarageStation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.SOLID.S01_SingleResponsibilityPrinciple_SRP 4 | { 5 | /// 6 | /// Sample used: https://www.dotnettricks.com/learn/designpatterns/solid-design-principles-explained-using-csharp 7 | /// 8 | public class GarageStation 9 | { 10 | private IGarageUtility _garageUtility; 11 | 12 | public GarageStation(IGarageUtility garageUtility) 13 | { 14 | _garageUtility = garageUtility; 15 | } 16 | 17 | public void OpenForService() 18 | { 19 | _garageUtility.TurnLightsOn(); 20 | _garageUtility.OpenDoors(); 21 | } 22 | 23 | public void CloseGarage() 24 | { 25 | _garageUtility.TurnLightsOff(); 26 | _garageUtility.CloseDoors(); 27 | } 28 | 29 | public void ServiceAVehicle() 30 | { 31 | Console.WriteLine("...servicing the vehicle!"); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SOLID/S01-SingleResponsibilityPrinciple_SRP/GarageUtility.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.SOLID.S01_SingleResponsibilityPrinciple_SRP 4 | { 5 | public class GarageUtility : IGarageUtility 6 | { 7 | public void CloseDoors() 8 | { 9 | Console.WriteLine("...closing the doors"); 10 | } 11 | 12 | public void OpenDoors() 13 | { 14 | Console.WriteLine("...opening the doors"); 15 | } 16 | 17 | public void TurnLightsOff() 18 | { 19 | Console.WriteLine("...turning on the lights"); 20 | } 21 | 22 | public void TurnLightsOn() 23 | { 24 | Console.WriteLine("...turning off the lights"); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SOLID/S01-SingleResponsibilityPrinciple_SRP/IGarageUtility.cs: -------------------------------------------------------------------------------- 1 | namespace CodeSamples.SOLID.S01_SingleResponsibilityPrinciple_SRP 2 | { 3 | public interface IGarageUtility 4 | { 5 | void OpenDoors(); 6 | void CloseDoors(); 7 | 8 | void TurnLightsOn(); 9 | void TurnLightsOff(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SOLID/S01-SingleResponsibilityPrinciple_SRP/SingleResponsibilityPrincipleSample.cs: -------------------------------------------------------------------------------- 1 | namespace CodeSamples.SOLID.S01_SingleResponsibilityPrinciple_SRP 2 | { 3 | public class SingleResponsibilityPrincipleSample : SampleExecute 4 | { 5 | public override void Execute() 6 | { 7 | Title("SOLID - SingleResponsibilityPrinciple"); 8 | Section("SRP"); 9 | 10 | var garage = new GarageStation(new GarageUtility()); 11 | garage.OpenForService(); 12 | garage.ServiceAVehicle(); 13 | garage.CloseGarage(); 14 | 15 | Finish(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SOLID/S04-InversionOfControl_IoC/Duck.cs: -------------------------------------------------------------------------------- 1 | namespace CodeSamples.SOLID.S04_InversionOfControl_IoC 2 | { 3 | public class Duck 4 | { 5 | private IDuckQuack _quack; 6 | private IDuckFly _fly; 7 | 8 | public Duck(IDuckQuack quack, IDuckFly fly) 9 | { 10 | this._quack = quack; 11 | this._fly = fly; 12 | } 13 | 14 | public void Quack() 15 | { 16 | _quack.Quack(); 17 | } 18 | 19 | public void Fly() 20 | { 21 | _fly.Fly(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SOLID/S04-InversionOfControl_IoC/Flys.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.SOLID.S04_InversionOfControl_IoC 4 | { 5 | public class JetFly : IDuckFly 6 | { 7 | public void Fly() 8 | { 9 | Console.WriteLine("....zzzzzzzzz......I'm flying very fast! Jet fast!"); 10 | } 11 | } 12 | 13 | public class NormalFly : IDuckFly 14 | { 15 | public void Fly() 16 | { 17 | Console.WriteLine("...quackin' my way in the clouds..."); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SOLID/S04-InversionOfControl_IoC/IDuckFly.cs: -------------------------------------------------------------------------------- 1 | namespace CodeSamples.SOLID.S04_InversionOfControl_IoC 2 | { 3 | public interface IDuckFly 4 | { 5 | void Fly(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SOLID/S04-InversionOfControl_IoC/IDuckQuack.cs: -------------------------------------------------------------------------------- 1 | namespace CodeSamples.SOLID.S04_InversionOfControl_IoC 2 | { 3 | public interface IDuckQuack 4 | { 5 | void Quack(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SOLID/S04-InversionOfControl_IoC/InversionOfControlSample.cs: -------------------------------------------------------------------------------- 1 | namespace CodeSamples.SOLID.S04_InversionOfControl_IoC 2 | { 3 | public class InversionOfControlSample : SampleExecute 4 | { 5 | public override void Execute() 6 | { 7 | Title("SOLID - InversionOfControl"); 8 | Section("Dependency Injection"); 9 | 10 | var amazingDuck = new Duck(new FrenchQuack(), new JetFly()); 11 | amazingDuck.Quack(); 12 | amazingDuck.Fly(); 13 | 14 | var weirdDuck = new Duck(new SpanishQuack(), new NormalFly()); 15 | weirdDuck.Quack(); 16 | weirdDuck.Fly(); 17 | 18 | Finish(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SOLID/S04-InversionOfControl_IoC/Quacks.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.SOLID.S04_InversionOfControl_IoC 4 | { 5 | public class FrenchQuack : IDuckQuack 6 | { 7 | public void Quack() 8 | { 9 | Console.WriteLine("Le Quack!"); 10 | } 11 | } 12 | 13 | public class SpanishQuack : IDuckQuack 14 | { 15 | public void Quack() 16 | { 17 | Console.WriteLine("Il Quacko!"); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SampleExecute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples 4 | { 5 | public abstract class SampleExecute : ISampleExecute 6 | { 7 | private void PopColors() 8 | { 9 | Console.ResetColor(); 10 | } 11 | 12 | private void SetTitleColor() 13 | { 14 | Console.ForegroundColor = ConsoleColor.Green; 15 | } 16 | 17 | private void SetSectionColor() 18 | { 19 | Console.ForegroundColor = ConsoleColor.Yellow; 20 | } 21 | 22 | public void Title(string title) 23 | { 24 | SetTitleColor(); 25 | Console.WriteLine(); 26 | Console.WriteLine(title); 27 | PopColors(); 28 | Console.WriteLine("============================================================"); 29 | } 30 | 31 | public void Section(string title) 32 | { 33 | SetSectionColor(); 34 | Console.WriteLine(title); 35 | PopColors(); 36 | Console.WriteLine("============================================================"); 37 | } 38 | 39 | public void LineBreak() 40 | { 41 | Console.WriteLine("============================================================"); 42 | } 43 | 44 | public void Finish() 45 | { 46 | Console.WriteLine("============================================================"); 47 | Console.WriteLine(); 48 | Console.WriteLine(); 49 | } 50 | 51 | //from interface 52 | //abstract methods MUST be implemented by derived class, because 53 | //they do not have implementation in abstract class 54 | public abstract void Execute(); 55 | 56 | //virtual methods do not have to be implemented by derived class, because 57 | //they have implementation in abstract class; they can be overriden in derived 58 | //class, if necessary 59 | public virtual void ExecuteVirtual() 60 | { 61 | Console.WriteLine("Executing Virtual Method in abstract class"); 62 | } 63 | 64 | //methods, that are not abstract or virtual, cannot be overriden in derived 65 | //class 66 | public void ExecuteNormal() 67 | { 68 | Console.WriteLine("Executing Method in abstract class"); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Settings.cs: -------------------------------------------------------------------------------- 1 | namespace CodeSamples.Properties { 2 | 3 | 4 | // This class allows you to handle specific events on the settings class: 5 | // The SettingChanging event is raised before a setting's value is changed. 6 | // The PropertyChanged event is raised after a setting's value is changed. 7 | // The SettingsLoaded event is raised after the setting values are loaded. 8 | // The SettingsSaving event is raised before the setting values are saved. 9 | internal sealed partial class Settings { 10 | 11 | public Settings() { 12 | // // To add event handlers for saving and changing settings, uncomment the lines below: 13 | // 14 | // this.SettingChanging += this.SettingChangingEventHandler; 15 | // 16 | // this.SettingsSaving += this.SettingsSavingEventHandler; 17 | // 18 | } 19 | 20 | private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) { 21 | // Add code to handle the SettingChangingEvent event here. 22 | } 23 | 24 | private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) { 25 | // Add code to handle the SettingsSaving event here. 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Settings/ConfigurationManagerSnippets.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Configuration; 3 | 4 | namespace CodeSamples.Settings 5 | { 6 | internal class ConfigurationManagerSnippets 7 | { 8 | /// 9 | /// Add following to App.config: 10 | /// 11 | /// 12 | /// ============================= 13 | /// 14 | /// 15 | /// 16 | /// 17 | /// ============================= 18 | /// 19 | /// 20 | /// 21 | private void ReadAllSettings() 22 | { 23 | try 24 | { 25 | var appSettings = ConfigurationManager.AppSettings; 26 | 27 | if (appSettings.Count == 0) 28 | { 29 | Console.WriteLine("AppSettings is empty."); 30 | } 31 | else 32 | { 33 | foreach (var key in appSettings.AllKeys) 34 | { 35 | Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]); 36 | } 37 | } 38 | } 39 | catch (ConfigurationErrorsException) 40 | { 41 | Console.WriteLine("Error reading app settings"); 42 | } 43 | } 44 | 45 | public void Run() 46 | { 47 | ReadAllSettings(); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Settings/SettingsSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Settings 4 | { 5 | public class SettingsSample : SampleExecute 6 | { 7 | private void LoadMainSettings() 8 | { 9 | Console.WriteLine($"SettingString = {Properties.Settings.Default.SettingString}"); 10 | Console.WriteLine($"SettingInt = {Properties.Settings.Default.SettingInt}"); 11 | } 12 | 13 | private void LoadOtherSettings() 14 | { 15 | Console.WriteLine($"SomeOtherStringSetting = {Properties.OtherSettings.Default.SomeOtherStringSetting}"); 16 | Console.WriteLine($"SomeOtherIntSetting = {Properties.OtherSettings.Default.SomeOtherIntSetting}"); 17 | } 18 | 19 | private void StoreMainSettings() 20 | { 21 | Properties.Settings.Default.SettingString = DateTime.Now.ToString(); 22 | Properties.Settings.Default.SettingInt = DateTime.Now.Second; 23 | Properties.Settings.Default.Save(); 24 | } 25 | 26 | private void StoreOtherSettings() 27 | { 28 | Properties.OtherSettings.Default.SomeOtherStringSetting = DateTime.Now.ToString(); 29 | Properties.OtherSettings.Default.SomeOtherIntSetting = DateTime.Now.Second; 30 | Properties.OtherSettings.Default.Save(); 31 | } 32 | 33 | public override void Execute() 34 | { 35 | Title("SettingsSampleExecute"); 36 | 37 | StoreMainSettings(); 38 | StoreOtherSettings(); 39 | 40 | LoadMainSettings(); 41 | LoadOtherSettings(); 42 | 43 | var configurationManagerSnippets = new ConfigurationManagerSnippets(); 44 | configurationManagerSnippets.Run(); 45 | 46 | Finish(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Structures/StructSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace CodeSamples.Structures 5 | { 6 | public class StructSample : SampleExecute 7 | { 8 | [StructLayout(LayoutKind.Explicit)] 9 | public struct FourBytesMakeAnInteger 10 | { 11 | 12 | public FourBytesMakeAnInteger(uint unsignedInteger) 13 | { 14 | A = 0; 15 | B = 0; 16 | C = 0; 17 | D = 0; 18 | UnsignedInteger = unsignedInteger; 19 | } 20 | 21 | public FourBytesMakeAnInteger(byte a, byte b, byte c, byte d) 22 | { 23 | UnsignedInteger = 0; 24 | A = a; 25 | B = b; 26 | C = c; 27 | D = d; 28 | } 29 | 30 | [FieldOffset(0)] 31 | public readonly byte A; 32 | 33 | [FieldOffset(1)] 34 | public readonly byte B; 35 | 36 | [FieldOffset(2)] 37 | public readonly byte C; 38 | 39 | [FieldOffset(3)] 40 | public readonly byte D; 41 | 42 | [FieldOffset(0)] 43 | public readonly uint UnsignedInteger; 44 | } 45 | 46 | 47 | [StructLayout(LayoutKind.Explicit)] 48 | public struct FloatAndUint 49 | { 50 | [FieldOffset(0)] 51 | public float FloatValue; 52 | 53 | [FieldOffset(0)] 54 | public uint UintValue; 55 | } 56 | 57 | [StructLayout(LayoutKind.Explicit)] 58 | public struct DoubleAndUlong 59 | { 60 | [FieldOffset(0)] 61 | public double DoubleValue; 62 | 63 | [FieldOffset(0)] 64 | public ulong UlongValue; 65 | } 66 | 67 | [Flags] 68 | internal enum DosFileAttributes : byte 69 | { 70 | None = 0, 71 | ReadOnly = 1, 72 | Archive = 2, 73 | Compressed = 4, 74 | Hidden = 8, 75 | System = 16, 76 | Encrypted = 32, 77 | Indexed = 64, 78 | Temporary = 128 79 | } 80 | 81 | internal enum DosFileOwnership : byte 82 | { 83 | None = 0, 84 | User = 1, 85 | System = 2, 86 | Administrator = 3, 87 | Network = 4, 88 | Domain = 5, 89 | Creator = 6, 90 | Editor = 7 91 | } 92 | 93 | [StructLayout(LayoutKind.Explicit)] 94 | internal struct EnumInStruct 95 | { 96 | [FieldOffset(0)] 97 | public uint FileHeader; 98 | 99 | [FieldOffset(2)] 100 | public DosFileOwnership Ownership; 101 | 102 | [FieldOffset(3)] 103 | public DosFileAttributes Attributes; 104 | } 105 | 106 | [StructLayout(LayoutKind.Explicit)] 107 | internal struct BoolToByte 108 | { 109 | [FieldOffset(0)] 110 | public bool BoolProperty; 111 | 112 | [FieldOffset(0)] 113 | public byte ByteProperty; 114 | } 115 | 116 | private void PrimitiveTypesSizes() 117 | { 118 | Console.WriteLine($"Size of 'sbyte' = {sizeof(sbyte)} bytes ({sizeof(sbyte) * 8} bits)"); 119 | Console.WriteLine($"Size of 'byte' = {sizeof(byte)} bytes ({sizeof(byte) * 8} bits)"); 120 | Console.WriteLine($"Size of 'short' = {sizeof(short)} bytes ({sizeof(short) * 8} bits)"); 121 | Console.WriteLine($"Size of 'ushort' = {sizeof(ushort)} bytes ({sizeof(ushort) * 8} bits)"); 122 | Console.WriteLine($"Size of 'int' = {sizeof(int)} bytes ({sizeof(int) * 8} bits)"); 123 | Console.WriteLine($"Size of 'uint' = {sizeof(uint)} bytes ({sizeof(uint) * 8} bits)"); 124 | Console.WriteLine($"Size of 'long' = {sizeof(long)} bytes ({sizeof(long) * 8} bits)"); 125 | Console.WriteLine($"Size of 'ulong' = {sizeof(ulong)} bytes ({sizeof(ulong) * 8} bits)"); 126 | Console.WriteLine($"Size of 'char' = {sizeof(char)} bytes ({sizeof(char) * 8} bits)"); 127 | Console.WriteLine($"Size of 'float' = {sizeof(float)} bytes ({sizeof(float) * 8} bits)"); 128 | Console.WriteLine($"Size of 'double' = {sizeof(double)} bytes ({sizeof(double) * 8} bits)"); 129 | Console.WriteLine($"Size of 'decimal' = {sizeof(decimal)} bytes ({sizeof(decimal) * 8} bits)"); 130 | Console.WriteLine($"Size of 'bool' = {sizeof(bool)} bytes ({sizeof(bool) * 8} bits)"); 131 | } 132 | 133 | public override void Execute() 134 | { 135 | Title("StructSampleExecute"); 136 | 137 | Section("Compose bytes into int"); 138 | var makeAnIntFromBytes = new FourBytesMakeAnInteger(0x11, 0x22, 0x33, 0x44); 139 | Console.WriteLine($"We have four bytes (0x{makeAnIntFromBytes.A:X2}, 0x{makeAnIntFromBytes.B:X2}, 0x{makeAnIntFromBytes.C:X2}, 0x{makeAnIntFromBytes.D:X2}), we composed them into an integer (0x{makeAnIntFromBytes.UnsignedInteger:X8})."); 140 | 141 | var makeBytesFromInt = new FourBytesMakeAnInteger(0xFFEEDDAA); 142 | Console.WriteLine($"We have an integer (0x{makeBytesFromInt.UnsignedInteger:X8}) we divided into four bytes (0x{makeBytesFromInt.A:X2}, 0x{makeBytesFromInt.B:X2}, 0x{makeBytesFromInt.C:X2}, 0x{makeBytesFromInt.D:X2})."); 143 | 144 | Section("Convert float to uint"); 145 | var floatAndUint = new FloatAndUint(); 146 | floatAndUint.FloatValue = 3.1415926f; 147 | Console.WriteLine($"We have a float ({floatAndUint.FloatValue}) we can show as uint (in hex) = (0x{floatAndUint.UintValue:X8})."); 148 | floatAndUint.UintValue = 0x40490fda; //PI in IEEE-754 format 149 | Console.WriteLine($"We have an uint (in hex) = (0x{floatAndUint.UintValue:X8}) we can show as float = ({floatAndUint.FloatValue})."); 150 | 151 | Section("Convert double to ulong"); 152 | var doubleAndUlong = new DoubleAndUlong(); 153 | doubleAndUlong.DoubleValue = Math.E; 154 | Console.WriteLine($"We have a double ({doubleAndUlong.DoubleValue}) we can show as ulong (in hex) = (0x{doubleAndUlong.UlongValue:X16})."); 155 | doubleAndUlong.UlongValue = 0x400921fb54442d18; //PI in IEEE-754 format 156 | Console.WriteLine($"We have an ulong (in hex) = (0x{doubleAndUlong.UlongValue:X16}) we can show as double = ({doubleAndUlong.DoubleValue})."); 157 | 158 | Section("Enum in struct"); 159 | var random = new Random(); 160 | byte attributes = (byte)random.Next(1, 255); 161 | byte ownership = (byte)(random.Next(1, 255) % 8); 162 | var enumInStruct = new EnumInStruct(); 163 | enumInStruct.FileHeader = (uint)((attributes << 24) | (ownership << 16) | 0x5678); 164 | Console.WriteLine($"We have a FileHeader (in hex) = (0x{enumInStruct.FileHeader:X8}), we can extract Attributes = ({enumInStruct.Attributes.ToString("g")}) and ownership = ({enumInStruct.Ownership.ToString("g")})."); 165 | 166 | Section("Boolean and bytes"); 167 | var boolToByte = new BoolToByte(); 168 | boolToByte.BoolProperty = false; 169 | Console.WriteLine($"We have a Bool Property = {boolToByte.BoolProperty}, we can convert to byte = 0x{boolToByte.ByteProperty:X2}."); 170 | boolToByte.BoolProperty = true; 171 | Console.WriteLine($"We have a Bool Property = {boolToByte.BoolProperty}, we can convert to byte = 0x{boolToByte.ByteProperty:X2}."); 172 | 173 | Section("Primitive types sizes"); 174 | PrimitiveTypesSizes(); 175 | 176 | Finish(); 177 | } 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SyntacticSugars/NullSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.SyntacticSugars 4 | { 5 | public class NullSample : SampleExecute 6 | { 7 | public override void Execute() 8 | { 9 | Title("NullSampleExecute"); 10 | 11 | Object obj = null; 12 | 13 | if(obj is null) 14 | { 15 | Console.WriteLine("Object is null."); 16 | } 17 | 18 | if (obj is object) 19 | { 20 | Console.WriteLine("Object is not null."); 21 | } 22 | 23 | Finish(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SyntacticSugars/PatternMatchingSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.SyntacticSugars 4 | { 5 | #region Test Classes 6 | public class Cat 7 | { 8 | public bool HasClaws => true; 9 | 10 | public void Voice() 11 | { 12 | Console.WriteLine("Meow"); 13 | } 14 | } 15 | 16 | public class Dog 17 | { 18 | public bool Bites => true; 19 | 20 | public void Bark() 21 | { 22 | Console.WriteLine("Woof"); 23 | } 24 | } 25 | 26 | public class Duck 27 | { 28 | public void Quack() 29 | { 30 | Console.WriteLine("Quack"); 31 | } 32 | } 33 | #endregion 34 | 35 | public class PatternMatchingSample : SampleExecute 36 | { 37 | private void DecideWhoIsIt(object obj) 38 | { 39 | switch(obj) 40 | { 41 | case Cat cat: 42 | cat.Voice(); 43 | break; 44 | case Dog dog when dog.Bites: 45 | dog.Bark(); 46 | break; 47 | case Duck duck: 48 | duck.Quack(); 49 | break; 50 | default: 51 | break; 52 | } 53 | } 54 | 55 | public override void Execute() 56 | { 57 | Title("PatternMatchingSampleExecute"); 58 | DecideWhoIsIt(new Cat()); 59 | DecideWhoIsIt(new Dog()); 60 | DecideWhoIsIt(new Duck()); 61 | Finish(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SyntacticSugars/PropertiesSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.SyntacticSugars 4 | { 5 | public class PropertiesSample: SampleExecute 6 | { 7 | #region Property Assignment 8 | private string _propertyName = "value"; 9 | 10 | //property getters/setter 11 | public string PropertyNameLong 12 | { 13 | get 14 | { 15 | return _propertyName; 16 | } 17 | set 18 | { 19 | _propertyName = value; 20 | } 21 | } 22 | 23 | //property short 24 | public string PropertyNameShort 25 | { 26 | get => _propertyName; 27 | set => _propertyName = value; 28 | } 29 | 30 | //expression bodied members 31 | public string ExpressionMember => $"{PropertyNameLong} {PropertyNameShort}"; 32 | #endregion 33 | 34 | public string AutoProperty { get; set; } 35 | public string AutoPropertyDefaultValueEmpty { get; set; } = String.Empty; 36 | public string AutoPropertyDefaultValueNotEmpty { get; set; } = "default property value"; 37 | 38 | public override void Execute() 39 | { 40 | Title("PropertiesExecute"); 41 | Console.WriteLine($"PropertyNameLong = {PropertyNameLong}"); 42 | Console.WriteLine($"PropertyNameShort = {PropertyNameShort}"); 43 | Console.WriteLine($"ExpressionMember = {ExpressionMember}"); 44 | Console.WriteLine($"AutoProperty = {AutoProperty}"); 45 | Console.WriteLine($"AutoPropertyDefaultValueEmpty = {AutoPropertyDefaultValueEmpty}"); 46 | Console.WriteLine($"AutoPropertyDefaultValueNotEmpty = {AutoPropertyDefaultValueNotEmpty}"); 47 | Finish(); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SyntacticSugars/StringInterpolationSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | 4 | namespace CodeSamples.SyntacticSugars 5 | { 6 | public class StringInterpolationSample : SampleExecute 7 | { 8 | public override void Execute() 9 | { 10 | Title("StringInterpolationSampleExecute"); 11 | int intVariable = 5; 12 | string stringVariable = "some value"; 13 | double doubleVariable = Math.PI; 14 | DateTime datetimeVariable = DateTime.Now; 15 | StringBuilder sb = new StringBuilder(); 16 | // 17 | sb.Append($"Integer = {intVariable}").Append(", "); 18 | sb.Append($"String = {stringVariable}").Append(", "); 19 | sb.Append($"Double (2 decimals) value = {doubleVariable:0.00}").Append(", "); 20 | sb.Append($"Double (2 decimals, leading zeroes) value = {doubleVariable:000.00}").Append(", "); 21 | sb.Append($"Double (5 decimals) = {doubleVariable:0.00000}").Append(", "); 22 | sb.Append($"DateTime (dd.MM.yyyy) = {datetimeVariable:dd.MM.yyyy}").Append(", "); 23 | sb.Append($"DateTime (yyyy-MM-dd) = {datetimeVariable:yyyy-MM-dd}"); 24 | // 25 | Console.WriteLine(sb.ToString()); 26 | Finish(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/SyntacticSugars/UsingSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.SyntacticSugars 4 | { 5 | public class MyDisposableClass : IDisposable 6 | { 7 | public void DoSomeStuff() 8 | { 9 | Console.WriteLine("...doing stuff"); 10 | } 11 | 12 | public void Dispose() 13 | { 14 | Console.WriteLine("Disposed"); 15 | } 16 | } 17 | 18 | public class UsingSample : SampleExecute 19 | { 20 | 21 | public override void Execute() 22 | { 23 | Title("UsingSampleExecute"); 24 | /* with "using" the code below is the same as: 25 | * var myDisposable = new MyDisposable(); 26 | * try 27 | * { 28 | * myDisposable.DoThing(); 29 | * } 30 | * finally 31 | * { 32 | * if (myDisposable != null) 33 | * { 34 | * ((IDisposable)myDisposable).Dispose(); 35 | * } 36 | * } 37 | */ 38 | using (var myDisposable = new MyDisposableClass()) 39 | { 40 | myDisposable.DoSomeStuff(); 41 | } 42 | Finish(); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Timing/TimingSample.cs: -------------------------------------------------------------------------------- 1 | namespace CodeSamples.Timing 2 | { 3 | public class TimingSample : SampleExecute 4 | { 5 | public override void Execute() 6 | { 7 | Title("TimingSample"); 8 | Section("Stopwatch Timing"); 9 | 10 | var stopwatchTiming = new TimingStopwatch(); 11 | stopwatchTiming.Go(); 12 | 13 | Finish(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Timing/TimingStopwatch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Threading; 4 | 5 | namespace CodeSamples.Timing 6 | { 7 | public class TimingStopwatch 8 | { 9 | private void StopwatchSampleCreateManually() 10 | { 11 | var stopWatch = new Stopwatch(); 12 | 13 | Console.Write("Going to sleep for a while, tired b/c of manual labor..."); 14 | stopWatch.Start(); 15 | Thread.Sleep(2000); 16 | stopWatch.Stop(); 17 | Console.WriteLine($"woke up after {stopWatch.Elapsed}, that is {stopWatch.Elapsed.TotalMilliseconds} ms."); 18 | } 19 | 20 | private void StopwatchSampleCreateAuto() 21 | { 22 | 23 | Console.Write("Going to sleep for a while, tired b/c of auto create..."); 24 | var stopWatch = Stopwatch.StartNew(); 25 | Thread.Sleep(2000); 26 | stopWatch.Stop(); 27 | Console.WriteLine($"woke up after {stopWatch.Elapsed}, that is {stopWatch.Elapsed.TotalMilliseconds} ms."); 28 | } 29 | 30 | public void Go() 31 | { 32 | StopwatchSampleCreateManually(); 33 | StopwatchSampleCreateAuto(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/TupleDeconstruction/TupleDeconstruction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.TupleDeconstruction 4 | { 5 | #region Worker Class 6 | public class User 7 | { 8 | public string FirstName { get; set; } 9 | public string LastName { get; set; } 10 | public int Age { get; set; } 11 | public string Email { get; set; } 12 | 13 | public void Deconstruct(out string firstName, out string lastName) 14 | { 15 | firstName = FirstName; 16 | lastName = LastName; 17 | } 18 | 19 | public void Deconstruct(out string firstName, out string lastName, out int age) 20 | { 21 | firstName = FirstName; 22 | lastName = LastName; 23 | age = Age; 24 | } 25 | 26 | public (string, int) GetNameAndAge() 27 | { 28 | return ($"{FirstName} {LastName}", Age); 29 | } 30 | 31 | public (string fullName, int age) GetNameAndAgeNamed() 32 | { 33 | return ($"{FirstName} {LastName}", Age); 34 | } 35 | } 36 | #endregion 37 | 38 | public class TupleDeconstructionSample : SampleExecute 39 | { 40 | public override void Execute() 41 | { 42 | var user = new User() 43 | { 44 | FirstName = "Name", 45 | LastName = "LastName", 46 | Email = "name.lastname@domain.com", 47 | Age = 42 48 | }; 49 | 50 | (var firstName1, var lastName1) = user; //using Deconstruct method 51 | (var firstName2, var lastName2, var age) = user; //using Deconstruct method 52 | 53 | var unnamedTuple = user.GetNameAndAge(); 54 | var namedTuple = user.GetNameAndAgeNamed(); 55 | (string tupleFullNameTyped, int tupleAgeTyped) = user.GetNameAndAge(); 56 | var (tupleFullNameVar, tupleAgeVar) = user.GetNameAndAge(); 57 | 58 | Title("TupleDeconstructionExecute"); 59 | Console.WriteLine($"First deconstruction: First Name = {firstName1}, Last Name = {lastName1}"); 60 | Console.WriteLine($"Second deconstruction: First Name = {firstName2}, Last Name = {lastName2}, Age = {age}"); 61 | Console.WriteLine($"Unnamed Tuple: Name = {unnamedTuple.Item1}, Age = {unnamedTuple.Item2}"); 62 | Console.WriteLine($"Named Tuple: Name = {namedTuple.fullName}, Age = {namedTuple.age}"); 63 | Console.WriteLine($"Typed Params: Name = {tupleFullNameTyped}, Age = {tupleAgeTyped}"); 64 | Console.WriteLine($"Untyped (var) Params: Name = {tupleFullNameVar}, Age = {tupleAgeVar}"); 65 | Finish(); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Useful/GarbageCollectionSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | 4 | /// 5 | /// System.Runtime.GCLatencyMode.SustainedLowLatency 6 | /// https://docs.microsoft.com/en-us/dotnet/api/system.runtime.gclatencymode?view=netcore-3.1 7 | /// 8 | /// Batch Disables garbage collection concurrency and reclaims 9 | /// objects in a batch call. This is the most intrusive mode. 10 | /// This mode is designed for maximum throughput at the 11 | /// expense of responsiveness. 12 | /// 13 | /// Interactive Enables garbage collection concurrency and reclaims 14 | /// objects while the application is running. This is 15 | /// the default mode for garbage collection on a 16 | /// workstation and is less intrusive than Batch. 17 | /// It balances responsiveness with throughput. This 18 | /// mode is equivalent to garbage collection on a 19 | /// workstation that is concurrent. 20 | /// 21 | /// LowLatency Enables garbage collection that is more conservative 22 | /// in reclaiming objects. Full collections occur only 23 | /// if the system is under memory pressure, whereas 24 | /// generation 0 and generation 1 collections might occur 25 | /// more frequently. This mode is not available for the 26 | /// server garbage collector. 27 | /// 28 | /// NoGCRegion Indicates that garbage collection is suspended while 29 | /// the app is executing a critical path. 30 | /// NoGCRegion is a read-only value; that is, you cannot 31 | /// assign the NoGCRegion value to the LatencyMode property. 32 | /// You specify the no GC region latency mode by calling the 33 | /// TryStartNoGCRegion method and terminate it by calling the 34 | /// EndNoGCRegion() method. 35 | /// 36 | /// SustainedLowLatency Enables garbage collection that tries to minimize latency 37 | /// over an extended period. The collector tries to perform 38 | /// only generation 0, generation 1, and concurrent 39 | /// generation 2 collections. Full blocking collections may 40 | /// still occur if the system is under memory pressure. 41 | /// 42 | 43 | namespace CodeSamples.Useful 44 | { 45 | internal class GarbageCollectionInfo 46 | { 47 | public int MaxGeneration { get; private set; } 48 | 49 | public int Generation0 { get; private set; } 50 | public int Generation1 { get; private set; } 51 | public int Generation2 { get; private set; } 52 | 53 | public long TotalMemory { get; private set; } 54 | 55 | public GarbageCollectionInfo() 56 | { 57 | MaxGeneration = GC.MaxGeneration; 58 | 59 | Generation0 = GC.CollectionCount(0); 60 | Generation1 = GC.CollectionCount(1); 61 | Generation2 = GC.CollectionCount(2); 62 | 63 | TotalMemory = GC.GetTotalMemory(false); 64 | } 65 | 66 | public override string ToString() 67 | { 68 | return $"GC Info: MaxGen={MaxGeneration}, Gen0={Generation0}, Gen1={Generation1}, Gen2={Generation2}, Total Memory={TotalMemory}"; 69 | } 70 | } 71 | 72 | internal class GarbageCollection 73 | { 74 | #pragma warning disable S1481 75 | private void MakeSomeGarbage() 76 | { 77 | Console.WriteLine("Making Garbage..."); 78 | for (int i = 0; i < 5000; i++) 79 | { 80 | var version = new Version(); 81 | } 82 | } 83 | #pragma warning restore S1481 84 | 85 | #pragma warning disable S1215 86 | private void ForceGarbageCollection() 87 | { 88 | var gc = new GarbageCollection(); 89 | 90 | var gcBefore = new GarbageCollectionInfo(); 91 | Console.WriteLine($"Before Garbage Collection: {gcBefore}"); 92 | gc.MakeSomeGarbage(); 93 | var gcAfterGeneratingGarbage = new GarbageCollectionInfo(); 94 | Console.WriteLine($"After Generating Garbage: {gcAfterGeneratingGarbage}"); 95 | 96 | GC.Collect(0); 97 | var gcAfterCleanupGen0 = new GarbageCollectionInfo(); 98 | Console.WriteLine($"After Garbage Collection of Gen0: {gcAfterCleanupGen0}"); 99 | 100 | GC.Collect(1); 101 | var gcAfterCleanupGen1 = new GarbageCollectionInfo(); 102 | Console.WriteLine($"After Garbage Collection of Gen1: {gcAfterCleanupGen1}"); 103 | 104 | GC.WaitForPendingFinalizers(); 105 | GC.Collect(2); 106 | 107 | var gcAfterCleanupGen2 = new GarbageCollectionInfo(); 108 | Console.WriteLine($"After Garbage Collection of Gen2: {gcAfterCleanupGen2}"); 109 | 110 | GC.WaitForPendingFinalizers(); 111 | GC.Collect(); 112 | 113 | var gcAfterCleanup = new GarbageCollectionInfo(); 114 | Console.WriteLine($"After Garbage Collection: {gcAfterCleanup}"); 115 | } 116 | #pragma warning restore S1215 117 | 118 | private void TurnGarbageCollectionOff() 119 | { 120 | Console.Write("Turning Garbage Collection into low latency (= off)..."); 121 | System.Runtime.GCSettings.LatencyMode = System.Runtime.GCLatencyMode.SustainedLowLatency; 122 | Console.WriteLine("done!"); 123 | } 124 | 125 | private void TurnGarbageCollectionOn() 126 | { 127 | Console.Write("Turning Garbage Collection into interactive (= on)..."); 128 | System.Runtime.GCSettings.LatencyMode = System.Runtime.GCLatencyMode.Interactive; 129 | Console.WriteLine("done!"); 130 | } 131 | 132 | public void Go() 133 | { 134 | TurnGarbageCollectionOff(); 135 | Thread.Sleep(1000); 136 | TurnGarbageCollectionOn(); 137 | 138 | ForceGarbageCollection(); 139 | } 140 | } 141 | 142 | public class GarbageCollectionSample : SampleExecute 143 | { 144 | public override void Execute() 145 | { 146 | Title("GarbageCollectionSample"); 147 | 148 | var garbageCollection = new GarbageCollection(); 149 | garbageCollection.Go(); 150 | 151 | Finish(); 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Useful/LinqSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Linq; 5 | 6 | namespace CodeSamples.Useful 7 | { 8 | #region Sample Class 9 | public sealed class LinqSampleClass : IEquatable 10 | { 11 | public string Name { get; set; } = String.Empty; 12 | public string LastName { get; set; } = String.Empty; 13 | public string Place { get; set; } = String.Empty; 14 | public int Age { get; set; } = 0; 15 | 16 | public bool Equals(LinqSampleClass other) 17 | { 18 | //compare only by name, lastname and place, disregard age 19 | if (other is null) return false; 20 | return (other.Name.Equals(Name) && other.LastName.Equals(LastName) && other.Place.Equals(Place)); 21 | } 22 | } 23 | #endregion 24 | 25 | public class LinqSample : SampleExecute 26 | { 27 | List _sampleList = new List(); 28 | 29 | private void PrepareList(int sampleCount) 30 | { 31 | #region Source Collections 32 | var names = new Collection() { "Sasha", "Ria", "Kaseem", "Eve", "Keegan", "Giacomo", "Alana", "Katelyn", 33 | "Wilma", "Lucius", "Herman", "Erasmus", "Eden", "Helen", "Nora", "Owen", 34 | "Chelsea", "Timon", "Frances", "Shellie", "Darryl", "Chantale", "Natalie", 35 | "Barclay", "Medge", "Emmanuel", "Tarik", "Jakeem", "Serena", "Ramona", 36 | "Jelani", "Daryl", "Adara", "Willow", "Colby", "Kieran", "Amaya", "Callum", 37 | "Rose", "Keith", "Derek", "Thane", "Guinevere", "Alea", "Kiona", "Karen", 38 | "Lacy", "Georgia", "Francis", "Madeson", "Lucian", "Zachery", "Clark", 39 | "Colleen", "George", "Jermaine", "Fitzgerald", "Heidi", "Ferris", "Salvador", 40 | "Channing", "Wesley", "Noel", "Nathaniel", "Lacey", "Paki", "Xandra", "Kim", 41 | "Mia", "Cameran", "Hasad", "Ariana", "Sydnee", "Blaze", "Madison", "Gary", 42 | "Kadeem", "Nayda", "Martena", "Lesley", "Tate", "Harrison", "Summer", "Lillian", 43 | "Tanner", "Harding", "John", "Hiroko", "Nathan", "Jocelyn", "Yael", "Kirsten", 44 | "Genevieve", "Alika", "Knox", "Perry" }; 45 | var lastNames = new Collection() { "Greer", "Lindsey", "Miller", "Casey", "Whitley", "O'connor", "Edwards", 46 | "Pace", "York", "Nicholson", "Pope", "Alvarado", "Powell", "Craig", "Stout", 47 | "Strong" }; 48 | var places = new Collection() { "Rio Verde", "Sherborne", "Bolano", "Waver", "Sclayn" }; 49 | #endregion 50 | 51 | int maxAvailableSamples = names.Count * lastNames.Count * places.Count; 52 | if (sampleCount > maxAvailableSamples) 53 | throw new ArgumentOutOfRangeException("sampleCount", $"Requested sample count ({sampleCount}) too big. Max available count is {maxAvailableSamples}"); 54 | 55 | #region Long list of names 56 | _sampleList = new List(); 57 | int count = 0; 58 | var random = new Random(); 59 | 60 | do 61 | { 62 | var sample = new LinqSampleClass() 63 | { 64 | Name = names[random.Next(names.Count)], 65 | LastName = lastNames[random.Next(lastNames.Count)], 66 | Place = places[random.Next(places.Count)], 67 | Age = random.Next(Constants.Linq.MinAge, Constants.Linq.MaxAge) 68 | }; 69 | //ensure only different persons by name, lastname and place 70 | if (!_sampleList.Contains(sample)) 71 | { 72 | _sampleList.Add(sample); 73 | count++; 74 | } 75 | } while (count < sampleCount); 76 | #endregion 77 | } 78 | 79 | public LinqSample() 80 | { 81 | PrepareList(Constants.Linq.MaxSamples); 82 | } 83 | 84 | private void SumAgeSimple() 85 | { 86 | int sumAge = _sampleList.Select(x => x.Age).Sum(); 87 | Console.WriteLine($"Sum with Select = {sumAge}"); 88 | //...or... 89 | sumAge = _sampleList.Sum(x => x.Age); 90 | Console.WriteLine($"Sum without Select = {sumAge}"); 91 | } 92 | 93 | private void AverageAge() 94 | { 95 | double avgAge = _sampleList.Select(x => x.Age).Average(); 96 | Console.WriteLine($"Average = {avgAge:N1}"); 97 | //...or... 98 | avgAge = _sampleList.Select(x => x.Age).Where(x => x > 5).Average(); 99 | Console.WriteLine($"Average when (age > 5) = {avgAge:N1}"); 100 | //...or... 101 | avgAge = _sampleList.Where(x => x.Age > 10).Select(x => x.Age).Average(); 102 | Console.WriteLine($"Average when (age > 10) = {avgAge:N1}"); 103 | } 104 | 105 | private void SumAgeByLastnameGrouping() 106 | { 107 | var ageLastnameGroups = 108 | from sample in _sampleList 109 | group sample by sample.LastName into sampleGroup 110 | select 111 | new 112 | { 113 | Group = sampleGroup.Key, 114 | SumAge = sampleGroup.Sum(x => x.Age), 115 | CountMembers = sampleGroup.Count() 116 | }; 117 | //use result 118 | foreach (var sample in ageLastnameGroups) 119 | { 120 | Console.WriteLine($"Lastname = {sample.Group}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}"); 121 | } 122 | } 123 | 124 | 125 | private void SumAgeByLastnameGroupingOrderedDescending() 126 | { 127 | var ageLastnameGroups = 128 | (from sample in _sampleList 129 | group sample by sample.LastName into sampleGroup 130 | select 131 | new 132 | { 133 | Group = sampleGroup.Key, 134 | SumAge = sampleGroup.Sum(x => x.Age), 135 | CountMembers = sampleGroup.Count() 136 | }).OrderByDescending(x => x.CountMembers); 137 | //use result 138 | foreach (var sample in ageLastnameGroups) 139 | { 140 | Console.WriteLine($"Lastname = {sample.Group}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}"); 141 | } 142 | } 143 | 144 | private void SumAgeByLastnameAndPlaceGrouping() 145 | { 146 | var ageLastnameGroups = 147 | from sample in _sampleList 148 | group sample by new { sample.LastName, sample.Place } into sampleGroup 149 | select 150 | new 151 | { 152 | GroupingKey = sampleGroup.Key, 153 | SumAge = sampleGroup.Sum(x => x.Age), 154 | CountMembers = sampleGroup.Count() 155 | }; 156 | //use result 157 | foreach (var sample in ageLastnameGroups) 158 | { 159 | Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}"); 160 | } 161 | } 162 | 163 | private void SumAgeByLastnameAndPlaceGroupingWithLet() 164 | { 165 | var ageLastnameGroups = 166 | from sample in _sampleList 167 | group sample by new 168 | { 169 | sample.LastName, 170 | sample.Place 171 | } 172 | into sampleGroup 173 | let sumAge = sampleGroup.Sum(x => x.Age) 174 | let memberCount = sampleGroup.Count() 175 | select 176 | new 177 | { 178 | GroupingKey = sampleGroup.Key, 179 | SumAge = sumAge, 180 | CountMembers = memberCount 181 | }; 182 | //use result 183 | foreach (var sample in ageLastnameGroups) 184 | { 185 | Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}"); 186 | } 187 | } 188 | 189 | private void SumAgeByLastnameAndPlaceGroupingOrdered() 190 | { 191 | var ageLastnameGroups = 192 | (from sample in _sampleList 193 | group sample by new { sample.LastName, sample.Place } into sampleGroup 194 | select 195 | new 196 | { 197 | GroupingKey = sampleGroup.Key, 198 | SumAge = sampleGroup.Sum(x => x.Age), 199 | CountMembers = sampleGroup.Count() 200 | }).OrderBy(x => x.CountMembers); 201 | //use result 202 | foreach (var sample in ageLastnameGroups) 203 | { 204 | Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}"); 205 | } 206 | } 207 | 208 | private void SumAgeByLastnameAndPlaceGroupingOrderedTop5() 209 | { 210 | var ageLastnameGroups = 211 | (from sample in _sampleList 212 | group sample by new { sample.LastName, sample.Place } into sampleGroup 213 | select 214 | new 215 | { 216 | GroupingKey = sampleGroup.Key, 217 | SumAge = sampleGroup.Sum(x => x.Age), 218 | CountMembers = sampleGroup.Count() 219 | }).OrderByDescending(x => x.CountMembers).Take(5); 220 | //use result 221 | foreach (var sample in ageLastnameGroups) 222 | { 223 | Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}"); 224 | } 225 | } 226 | 227 | private void SumAgeByLastnameAndPlaceGroupingOrderedSecond5() 228 | { 229 | var ageLastnameGroups = 230 | (from sample in _sampleList 231 | group sample by new { sample.LastName, sample.Place } into sampleGroup 232 | select 233 | new 234 | { 235 | GroupingKey = sampleGroup.Key, 236 | SumAge = sampleGroup.Sum(x => x.Age), 237 | CountMembers = sampleGroup.Count() 238 | }).OrderByDescending(x => x.CountMembers).Skip(5).Take(5); 239 | //use result 240 | foreach (var sample in ageLastnameGroups) 241 | { 242 | Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}"); 243 | } 244 | } 245 | 246 | private void SumAgeByLastnameAndPlaceGroupingOrderedLast5() 247 | { 248 | var ageLastnameGroups = 249 | (from sample in _sampleList 250 | group sample by new { sample.LastName, sample.Place } into sampleGroup 251 | select 252 | new 253 | { 254 | GroupingKey = sampleGroup.Key, 255 | SumAge = sampleGroup.Sum(x => x.Age), 256 | CountMembers = sampleGroup.Count() 257 | }).OrderByDescending(x => x.CountMembers); 258 | var last5AgeLastnameGroups = ageLastnameGroups.Skip(Math.Max(0, ageLastnameGroups.Count() - 5)); 259 | //use result 260 | foreach (var sample in last5AgeLastnameGroups) 261 | { 262 | Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}"); 263 | } 264 | } 265 | 266 | private void SumAgeByLastnameAndPlaceGroupingOrderedTwice() 267 | { 268 | var ageLastnameGroups = 269 | (from sample in _sampleList 270 | group sample by new { sample.LastName, sample.Place } into sampleGroup 271 | select 272 | new 273 | { 274 | GroupingKey = sampleGroup.Key, 275 | SumAge = sampleGroup.Sum(x => x.Age), 276 | CountMembers = sampleGroup.Count() 277 | }).OrderBy(x => x.GroupingKey.Place).ThenBy(x => x.CountMembers); 278 | //use result 279 | foreach (var sample in ageLastnameGroups) 280 | { 281 | Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}"); 282 | } 283 | } 284 | 285 | private void ListPeopleBetweenTwoAges(int lowerBound, int upperBound) 286 | { 287 | var nameList = 288 | from sample in _sampleList 289 | where sample.Age >= lowerBound && sample.Age <= upperBound 290 | select new { Name = sample.Name + " " + sample.LastName, sample.Age }; 291 | 292 | //use result 293 | foreach (var sample in nameList) 294 | { 295 | Console.WriteLine($"Name = {sample.Name}, Age = {sample.Age}"); 296 | } 297 | } 298 | 299 | public override void Execute() 300 | { 301 | Title("LinqSampleExecute"); 302 | SumAgeSimple(); 303 | LineBreak(); 304 | AverageAge(); 305 | LineBreak(); 306 | Section("Group by LastName"); 307 | SumAgeByLastnameGrouping(); 308 | LineBreak(); 309 | Section("Group by LastName and Place"); 310 | SumAgeByLastnameAndPlaceGrouping(); 311 | LineBreak(); 312 | Section("Group by LastName and Place (using 'let' keyword)"); 313 | SumAgeByLastnameAndPlaceGroupingWithLet(); 314 | LineBreak(); 315 | Section("Group by LastName (ordered by member count, desc)"); 316 | SumAgeByLastnameGroupingOrderedDescending(); 317 | LineBreak(); 318 | Section("Group by LastName and Place (ordered by member count)"); 319 | SumAgeByLastnameAndPlaceGroupingOrdered(); 320 | LineBreak(); 321 | Section("Group by LastName and Place (ordered by place and member count)"); 322 | SumAgeByLastnameAndPlaceGroupingOrderedTwice(); 323 | LineBreak(); 324 | Section("Group by LastName and Place (top 5, ordered by member count)"); 325 | SumAgeByLastnameAndPlaceGroupingOrderedTop5(); 326 | LineBreak(); 327 | Section("Group by LastName and Place (records 6..10, ordered by member count)"); 328 | SumAgeByLastnameAndPlaceGroupingOrderedSecond5(); 329 | LineBreak(); 330 | Section("Group by LastName and Place (last 5, ordered by member count)"); 331 | SumAgeByLastnameAndPlaceGroupingOrderedLast5(); 332 | LineBreak(); 333 | Section("People between ages 15 and 35"); 334 | ListPeopleBetweenTwoAges(15, 35); 335 | Finish(); 336 | } 337 | } 338 | } 339 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Useful/OverflowCheckSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Useful 4 | { 5 | public class OverflowCheckSample : SampleExecute 6 | { 7 | public override void Execute() 8 | { 9 | Title("OverflowCheckSampleExecute"); 10 | 11 | int firstValue; 12 | int secondValue; 13 | 14 | int maxValue = 2147483647; 15 | const int maxInt = int.MaxValue; 16 | 17 | //do not check for overflow 18 | unchecked 19 | { 20 | firstValue = 2147483647 + 100; 21 | } 22 | Console.WriteLine($"Unchecked sum 1 (in block) (overflow) = {firstValue}"); 23 | //...or... 24 | firstValue = unchecked(maxInt + 100); 25 | 26 | Console.WriteLine($"Unchecked sum 1 (inline) (overflow) = {firstValue}"); 27 | 28 | //unchecked by default at compile time and run time because it contains variables 29 | secondValue = maxValue + 100; 30 | Console.WriteLine($"Unchecked sum 2 (variabled added) (overflow) = {secondValue}"); 31 | 32 | //catch overflow at run time 33 | try 34 | { 35 | checked 36 | { 37 | secondValue = maxValue + 100; 38 | } 39 | Console.WriteLine($"Unchecked sum 2 (in block) (overflow) = {secondValue}"); 40 | //...or... 41 | secondValue = unchecked(maxValue + 100); 42 | Console.WriteLine($"Unchecked sum 2 (inline) (overflow) = {secondValue}"); 43 | } 44 | catch (Exception e) 45 | { 46 | Console.WriteLine($"Exception '{e.GetType().Name}' with message '{e.Message}' was thrown."); 47 | } 48 | 49 | Finish(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/Useful/ResultSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.Useful 4 | { 5 | internal class Result 6 | { 7 | public static Result Success(T obj) 8 | { 9 | return new Result(true, obj); 10 | } 11 | 12 | public static Result Error(string errorMessage) 13 | { 14 | return new Result(false, errorMessage); 15 | } 16 | } 17 | 18 | internal class Result 19 | { 20 | public bool IsSuccess { get; private set; } 21 | public T Value { get; private set; } 22 | 23 | public string ErrorMessage { get; private set; } 24 | 25 | public Result(bool success, T obj = default) 26 | { 27 | IsSuccess = success; 28 | Value = obj; 29 | } 30 | 31 | public Result(bool success, string message) 32 | { 33 | IsSuccess = success; 34 | ErrorMessage = message; 35 | } 36 | } 37 | 38 | public class ResultSample : SampleExecute 39 | { 40 | private Result ReturnSuccessful() 41 | { 42 | return Result.Success(4); 43 | } 44 | 45 | private Result ReturnError() 46 | { 47 | return Result.Error("Something went wrong!"); 48 | } 49 | 50 | public override void Execute() 51 | { 52 | Title("ResultSampleExecute"); 53 | 54 | var success = ReturnSuccessful(); 55 | 56 | if (success.IsSuccess) 57 | { 58 | Console.WriteLine($"Yey! Call was Successful, result is {success.Value}"); 59 | } 60 | 61 | var error = ReturnError(); 62 | 63 | if (!error.IsSuccess) 64 | { 65 | Console.WriteLine($"Oops! There was an error with message '{error.ErrorMessage}'"); 66 | } 67 | 68 | Finish(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/UsefulClasses/CollectionInitializerSamples.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Linq; 5 | 6 | namespace CodeSamples.UsefulClasses 7 | { 8 | public class CollectionInitializerSamples : SampleExecute 9 | { 10 | private void Lists() 11 | { 12 | var list = new List() { 1, 2, 3 }; 13 | Console.WriteLine($"List Contents: {string.Join(", ", list)}"); 14 | 15 | list.Add(12); 16 | Console.WriteLine($"List Contents After Addition: {string.Join(", ", list)}"); 17 | } 18 | 19 | private void Collections() 20 | { 21 | var collection = new Collection() { 1, 2, 3 }; 22 | Console.WriteLine($"Collection Contents: {string.Join(", ", collection)}"); 23 | 24 | collection.Add(21); 25 | Console.WriteLine($"Collection Contents After Addition: {string.Join(", ", collection)}"); 26 | } 27 | 28 | private void Dictionaries() 29 | { 30 | var dictionary = new Dictionary() 31 | { 32 | ["one"] = 1, 33 | ["two"] = 2, 34 | ["three"] = 3 35 | }; 36 | Console.WriteLine($"Collection Contents: {string.Join(", ", dictionary.Select(kv => kv.Key + "=" + kv.Value).ToArray())}"); 37 | 38 | dictionary.Add("zero", 0); 39 | Console.WriteLine($"Collection Contents After Addition: {string.Join(", ", dictionary.Select(kv => kv.Key + "=" + kv.Value).ToArray())}"); 40 | } 41 | 42 | private void Arrays() 43 | { 44 | var array = new int[] { 4, 5, 6 }; 45 | Console.WriteLine($"Array Contents: {string.Join(", ", array)}"); 46 | 47 | //array resize 48 | Array.Resize(ref array, 4); 49 | array[3] = 55; 50 | Console.WriteLine($"Array Contents After Resize & Addition: {string.Join(", ", array)}"); 51 | } 52 | 53 | public override void Execute() 54 | { 55 | Title("CollectionInitializerSamplesExecute"); 56 | 57 | Section("Lists"); 58 | Lists(); 59 | 60 | Section("Collections"); 61 | Collections(); 62 | 63 | Section("Arrays"); 64 | Arrays(); 65 | 66 | Section("Dictionaries"); 67 | Dictionaries(); 68 | 69 | Finish(); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/UsefulClasses/Dictionaries.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Collections.Specialized; 5 | 6 | namespace CodeSamples.UsefulClasses 7 | { 8 | public class DictionariesSample : SampleExecute 9 | { 10 | private Dictionary _ordinaryDictionary = new Dictionary(); 11 | private OrderedDictionary _orderedDictionary = new OrderedDictionary(); 12 | private SortedDictionary _sortedDictionary = new SortedDictionary(); 13 | 14 | private void AddToDictionaries() 15 | { 16 | #region Ordinary Dictionary 17 | _ordinaryDictionary.Add(1, "one"); 18 | _ordinaryDictionary.Add(3, "three"); 19 | _ordinaryDictionary.Add(2, "two"); 20 | #endregion 21 | 22 | #region Ordered Dictionary 23 | _orderedDictionary.Add(2, "ordered two"); 24 | _orderedDictionary.Add(1, "ordered one"); 25 | _orderedDictionary.Add(3, "ordered three"); 26 | #endregion 27 | 28 | #region Sorted Dictionary 29 | _sortedDictionary.Add(3, "sorted three"); 30 | _sortedDictionary.Add(2, "sorted two"); 31 | _sortedDictionary.Add(1, "sorted one"); 32 | #endregion 33 | } 34 | 35 | public override void Execute() 36 | { 37 | AddToDictionaries(); 38 | 39 | Title("DictionariesExecute"); 40 | //Ordinary dictionary - key must be present; in this case, 1 is the key and should return string "one" 41 | //the order of elements is not fixed, usually the same as they were added 42 | Section("Ordinary Dictionary"); 43 | foreach (KeyValuePair ordinaryElement in _ordinaryDictionary) 44 | { 45 | Console.WriteLine($"{ordinaryElement.Key} = {ordinaryElement.Value}"); 46 | } 47 | LineBreak(); 48 | 49 | //Ordered dictionary - Maintains order of elements, by which they were inserted 50 | Section("Ordered Dictionary (foreach)"); 51 | foreach (DictionaryEntry orderedElement in _orderedDictionary) 52 | { 53 | Console.WriteLine($"{orderedElement.Key} = {orderedElement.Value}"); 54 | } 55 | LineBreak(); 56 | Section("Ordered Dictionary (index)"); 57 | for (int i = 0; i < _orderedDictionary.Count; i++) 58 | { 59 | var orderedElement = _orderedDictionary[i]; 60 | Console.WriteLine($"{orderedElement}"); 61 | } 62 | LineBreak(); 63 | 64 | //Sorted dictionary - elements are sorted by key 65 | Section("Sorted Dictionary"); 66 | foreach (KeyValuePair sortedElement in _sortedDictionary) 67 | { 68 | Console.WriteLine($"{sortedElement.Key} = {sortedElement.Value}"); 69 | } 70 | 71 | Finish(); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/UsefulClasses/ObjectPoolSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | 4 | namespace CodeSamples.UsefulClasses 5 | { 6 | #region ObjectPool Class 7 | public class ObjectPool 8 | { 9 | private ConcurrentBag _objects; 10 | private Func _objectGenerator; 11 | 12 | public ObjectPool(Func objectGenerator) 13 | { 14 | if (objectGenerator == null) throw new ArgumentNullException("objectGenerator"); 15 | _objects = new ConcurrentBag(); 16 | _objectGenerator = objectGenerator; 17 | } 18 | 19 | public T GetObject() 20 | { 21 | T item; 22 | if (_objects.TryTake(out item)) return item; 23 | return _objectGenerator(); 24 | } 25 | 26 | public void PutObject(T item) 27 | { 28 | _objects.Add(item); 29 | } 30 | } 31 | #endregion 32 | 33 | #region Worker Class 34 | public class MyWorkerClass 35 | { 36 | public MyWorkerClass() 37 | { 38 | Console.WriteLine("Generated worker..."); 39 | } 40 | 41 | public void DoSomething() 42 | { 43 | Console.WriteLine("...done something"); 44 | } 45 | } 46 | #endregion 47 | 48 | public class ObjectPoolSample: SampleExecute 49 | { 50 | private ObjectPool _pool = new ObjectPool(() => new MyWorkerClass()); 51 | 52 | public override void Execute() 53 | { 54 | Title($"ObjectPoolExecute"); 55 | for(int i = 0; i < 5; i++) 56 | { 57 | //only 1 worker class will be created and then reused 58 | var worker = _pool.GetObject(); 59 | worker.DoSomething(); 60 | _pool.PutObject(worker); 61 | } 62 | Finish(); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/UsefulClasses/SpanSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CodeSamples.UsefulClasses 4 | { 5 | public class SpanSample : SampleExecute 6 | { 7 | private void SpanOverArray() 8 | { 9 | //var arrayOfInt = new int[100]; 10 | //var span = new Span(arrayOfInt); 11 | 12 | //byte data = 0; 13 | //for (int ctr = 0; ctr < arraySpan.Length; ctr++) 14 | // arraySpan[ctr] = data++; 15 | } 16 | 17 | private void SpanOverNativeMemory() 18 | { 19 | //var native = Marshal.AllocHGlobal(100); 20 | //Span nativeSpan; 21 | //unsafe 22 | //{ 23 | // nativeSpan = new Span(native.ToPointer(), 100); 24 | //} 25 | } 26 | 27 | public override void Execute() 28 | { 29 | throw new NotImplementedException(); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /CSharp Code Samples/CodeSamples/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # C# Code Examples (mostly for myself) 2 | 3 | A collection of code samples I have used C# and think they might be useful in the future. 4 | 5 | ## Sample Categories 6 | * [Abstract Class](CSharp%20Code%20Samples/CodeSamples/SampleExecute.cs) 7 | * [Anonymous Types](CSharp%20Code%20Samples/CodeSamples/Classes/AnonymousTypesSample.cs) 8 | * [Attributes and Conditionals](CSharp%20Code%20Samples/CodeSamples/Attributes) 9 | * [Debugger](CSharp%20Code%20Samples/CodeSamples/Attributes/DebuggingSample.cs) 10 | * [`DebuggerDisplay`](CSharp%20Code%20Samples/CodeSamples/Attributes/DebuggingSample.cs) 11 | * [`DebuggerBrowsable`](CSharp%20Code%20Samples/CodeSamples/Attributes/DebuggingSample.cs) 12 | * [`Conditional`](CSharp%20Code%20Samples/CodeSamples/Attributes/DebuggingSample.cs) 13 | * [`#if - #define - #endif`](CSharp%20Code%20Samples/CodeSamples/Attributes/DebuggingSample.cs) 14 | * [`Obsolete`](CSharp%20Code%20Samples/CodeSamples/Attributes/ObsoleteSample.cs) 15 | * [Compiler Warning](CSharp%20Code%20Samples/CodeSamples/Attributes/ObsoleteSample.cs) 16 | * [Compiler Error](CSharp%20Code%20Samples/CodeSamples/Attributes/ObsoleteSample.cs) 17 | * [`Conditional`](CSharp%20Code%20Samples/CodeSamples/Attributes/ConditionalSample.cs) 18 | * [Classes](CSharp%20Code%20Samples/CodeSamples/Classes) 19 | * [Get current Class name](CSharp%20Code%20Samples/CodeSamples/Classes/ClassAndMethodNamesSample.cs#L9) 20 | * [Get current Method Name](CSharp%20Code%20Samples/CodeSamples/Classes/ClassAndMethodNamesSample.cs#L10) 21 | * [Constructor Chaining](CSharp%20Code%20Samples/CodeSamples/Classes/ConstructorChainingSample.cs) 22 | * [Caller Info](CSharp%20Code%20Samples/CodeSamples/Classes/CallerInfoSample.cs) 23 | * [Comparing](CSharp%20Code%20Samples/CodeSamples/Classes) 24 | * [`IEquatable`](CSharp%20Code%20Samples/CodeSamples/Comparing/Equatable.cs) Additional links: [Link](https://bettersolutions.com/csharp/interfaces/iequatable.htm) 25 | * [`IEqualityComparer`](CSharp%20Code%20Samples/CodeSamples/Comparing/EqualityComparer.cs) Additional links: [Link](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.iequalitycomparer-1) 26 | * [Design Patterns](CSharp%20Code%20Samples/CodeSamples/Patterns) 27 | * Creational Patterns 28 | * [Singleton Pattern](CSharp%20Code%20Samples/CodeSamples/Patterns/Creational/SingletonPattern.cs) 29 | * [Factory Method Pattern](CSharp%20Code%20Samples/CodeSamples/Patterns/Creational/FactoryMethodPattern.cs) 30 | * [Abstract Factory Pattern](CSharp%20Code%20Samples/CodeSamples/Patterns/Creational/AbstractFactoryPattern.cs) 31 | * Behavioral Patterns 32 | * [Strategy Pattern](CSharp%20Code%20Samples/CodeSamples/Patterns/Behavioral/StrategyPattern.cs) 33 | * [Observer Pattern](CSharp%20Code%20Samples/CodeSamples/Patterns/Behavioral/ObserverPattern.cs) 34 | * [State Pattern](CSharp%20Code%20Samples/CodeSamples/Patterns/Behavioral/StatePattern.cs) 35 | * [Dictionaries](CSharp%20Code%20Samples/CodeSamples/UsefulClasses/Dictionaries.cs) 36 | * [`Dictionary`](CSharp%20Code%20Samples/CodeSamples/UsefulClasses/Dictionaries.cs#L42) Additional links: [Link](https://www.dotnetperls.com/dictionary) 37 | * [`OrderedDictionary`](CSharp%20Code%20Samples/CodeSamples/UsefulClasses/Dictionaries.cs#L50) (requires [`System.Collections.Specialized`](https://www.nuget.org/packages/System.Collections.Specialized/)); Additional links: [Link](https://www.geeksforgeeks.org/c-sharp-ordereddictionary-class/) 38 | * [`SortedDictionary`](CSharp%20Code%20Samples/CodeSamples/UsefulClasses/Dictionaries.cs#L65) Additional links: [Link](https://www.dotnetperls.com/sorteddictionary) 39 | * [Extension Methods](CSharp%20Code%20Samples/CodeSamples/Alterations/Extensions/ClassExtensionSample.cs) 40 | * [Garbage Collection](CSharp%20Code%20Samples/CodeSamples/Useful/GarbageCollectionSample.cs) 41 | * [Implicit/Explicit Conversion operators](CSharp%20Code%20Samples/CodeSamples/Alterations/EntityConversionSample.cs) 42 | * [Interface](CSharp%20Code%20Samples/CodeSamples/ISampleExecute.cs) 43 | * [`LINQ`](CSharp%20Code%20Samples/CodeSamples/Useful/LinqSample.cs) 44 | * Sum 45 | * Sum by Groups 46 | * Ordering (asc, desc) 47 | * Skipping 48 | * Take N elements 49 | * Select Samples with value between 50 | * [Object Pool](CSharp%20Code%20Samples/CodeSamples/UsefulClasses/ObjectPoolSample.cs) 51 | * [Operator Overloading](CSharp%20Code%20Samples/CodeSamples/Alterations/OperatorOverloadingSample.cs) Additional links: [Link](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading) 52 | * [SOLID](CSharp%20Code%20Samples/CodeSamples/SOLID) 53 | * [Single Responsibility Principle](CSharp%20Code%20Samples/CodeSamples/SOLID/S01-SingleResponsibilityPrinciple_SRP) 54 | * [Inversion of Control](CSharp%20Code%20Samples/CodeSamples/SOLID/S04-InversionOfControl_IoC) 55 | * [Syntactic Sugars](CSharp%20Code%20Samples/CodeSamples/SyntacticSugars) 56 | * [Auto Property](CSharp%20Code%20Samples/CodeSamples/SyntacticSugars/PropertiesSample.cs#L34) 57 | * [Auto Property with default value](CSharp%20Code%20Samples/CodeSamples/SyntacticSugars/PropertiesSample.cs#L35) 58 | * [Property getter/setter](CSharp%20Code%20Samples/CodeSamples/SyntacticSugars/PropertiesSample.cs#L11) 59 | * [String Interpolation](CSharp%20Code%20Samples/CodeSamples/SyntacticSugars/StringInterpolationSample.cs) 60 | * [Using](CSharp%20Code%20Samples/CodeSamples/SyntacticSugars/UsingSample.cs) 61 | * [Pattern Matching](CSharp%20Code%20Samples/CodeSamples/SyntacticSugars/PatternMatchingSample.cs) 62 | * [Threading](CSharp%20Code%20Samples/CodeSamples/MultiThreading) 63 | * [`BackgroundWorker`](CSharp%20Code%20Samples/CodeSamples/MultiThreading/BackgroundWorkerSample.cs) 64 | * [`Thread`](CSharp%20Code%20Samples/CodeSamples/MultiThreading/ThreadSample.cs) 65 | * [Timing](CSharp%20Code%20Samples/CodeSamples/Timing) 66 | * [Tuple Deconstruction](CSharp%20Code%20Samples/CodeSamples/TupleDeconstruction) (requires [`System.ValueTuple`](https://www.nuget.org/packages/System.ValueTuple/)); Additional links: [Link](https://docs.microsoft.com/en-us/dotnet/csharp/deconstruct) 67 | 68 | 69 | ## Useful Libraries 70 | 71 | ### Universal 72 | * Excel (Native) 73 | * [EPPlus](https://github.com/JanKallman/EPPlus) 74 | * QR Codes 75 | * [QRCoder](https://github.com/codebude/QRCoder) 76 | * PDF 77 | * [PdfFileWriter.NET](https://github.com/jeske/PdfFileWriter.NET) 78 | * JSON 79 | * [Json.NET](https://www.newtonsoft.com/json) 80 | * [Jil - Fast .NET JSON (De)Serializer, Built On Sigil](https://github.com/kevin-montrose/Jil) 81 | * Logging 82 | * [NLog](https://nlog-project.org/) 83 | * ORM 84 | * [AutoMapper](https://automapper.org/) 85 | 86 | ### WPF Specific 87 | * UI/UX 88 | * Frameworks 89 | * [MahApps.Metro](https://github.com/MahApps/MahApps.Metro) 90 | * [Modern UI for WPF](https://github.com/firstfloorsoftware/mui) 91 | * Iconpacks 92 | * [MahApps.IconPack](https://github.com/MahApps/MahApps.Metro.IconPacks) 93 | --------------------------------------------------------------------------------