├── .gitignore ├── CSharpGenerics.sln ├── LICENSE ├── README.md └── src ├── .vscode ├── launch.json └── tasks.json ├── M2.zip ├── M2 ├── after │ ├── Interfaces │ │ ├── .vscode │ │ │ ├── launch.json │ │ │ └── tasks.json │ │ ├── Constraints.cs │ │ ├── Interfaces.csproj │ │ ├── Interfaces.sln │ │ └── Program.cs │ └── WithoutGenerics │ │ ├── Inbox.cs │ │ ├── Memo.cs │ │ ├── MemoStack.cs │ │ ├── Program.cs │ │ ├── Stack.cs │ │ ├── UnitTests │ │ ├── Stack_Pop.cs │ │ └── Stack_Push.cs │ │ └── WithoutGenerics.csproj └── before │ └── README.md ├── M3 ├── after │ └── ReflectionVariance │ │ ├── ReflectionVariance.ConsoleApp │ │ ├── .vscode │ │ │ ├── launch.json │ │ │ └── tasks.json │ │ ├── ContravarianceSamples.cs │ │ ├── CovarianceSamples.cs │ │ ├── Program.cs │ │ ├── ReflectionSamples.cs │ │ ├── ReflectionVariance.ConsoleApp.csproj │ │ └── VarianceSamples.cs │ │ └── ReflectionVariance.sln └── before │ └── README.md ├── M4 └── after │ └── ClassesMethods │ ├── .vscode │ ├── launch.json │ └── tasks.json │ ├── BasicDefinitions.cs │ ├── Cache.cs │ ├── ClassesMethods.csproj │ ├── Commands.cs │ ├── Complexity.cs │ ├── Counter.cs │ ├── Extensions.cs │ ├── FluentGenerics.cs │ ├── GenericStatic.cs │ ├── Program.cs │ └── Repositories.cs └── M5 └── after └── EventsDelegates ├── .vscode ├── launch.json └── tasks.json ├── BaseRepositories.cs ├── BuiltinDelegates.cs ├── DataLoader.cs ├── Delegates.cs ├── EventsDelegates.csproj ├── EventsDelegates.sln ├── Program.cs └── Repositories.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | src/M3.zip 352 | src/M4.zip 353 | -------------------------------------------------------------------------------- /CSharpGenerics.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.6.30114.105 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WithoutGenerics", "WithoutGenerics\WithoutGenerics.csproj", "{26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Debug|x64 = Debug|x64 12 | Debug|x86 = Debug|x86 13 | Release|Any CPU = Release|Any CPU 14 | Release|x64 = Release|x64 15 | Release|x86 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Debug|x64.ActiveCfg = Debug|Any CPU 21 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Debug|x64.Build.0 = Debug|Any CPU 22 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Debug|x86.ActiveCfg = Debug|Any CPU 23 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Debug|x86.Build.0 = Debug|Any CPU 24 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Release|x64.ActiveCfg = Release|Any CPU 27 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Release|x64.Build.0 = Release|Any CPU 28 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Release|x86.ActiveCfg = Release|Any CPU 29 | {26BA3E06-C228-4DEF-B2E9-9A316B46EEA3}.Release|x86.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {0B42A56A-6C66-456E-A32D-D421D207953B} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Steve Smith 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pluralsight C# Generics: Best Practices Samples 2 | 3 | Sample code for the [Pluralsight C# Generics: Best Practices course](https://www.pluralsight.com/courses/working-c-sharp-generics-best-practices) by [Steve "ardalis" Smith](https://pluralsight.com/authors/steve-smith). 4 | 5 | ## Give a Star! :star: 6 | 7 | If you like or are using this project to learn, please give it a star. Thanks! 8 | 9 | ## Course Details 10 | 11 | The C# Generics: Best Practices course covers the following topics: 12 | 13 | * Working with Generic Interfaces and Constraints 14 | * Understanding Covariance and Contravariance 15 | * Using Reflection with Generic Types 16 | * Implementing Generic Classes (and sub/super classes) 17 | * Implementing Generic Methods 18 | * When to use Generic Classes vs. Generic Methods 19 | * Raising and Handling Generic Events 20 | * Working with Generic Delegates 21 | * Understanding `Predicate` 22 | * Understanding `Action` 23 | * Understanding `Func` 24 | 25 | ## Need Help? 26 | 27 | If you have specific questions about the course, ask them in the course discussion tab on Pluralsight. 28 | 29 | If you find a bug in the samples, [post an issue here](https://github.com/ardalis/CSharpGenerics/issues). 30 | 31 | If you need training for your team, contact Steve via [NimblePros.com](https://nimblepros.com). 32 | 33 | If you'd like to join Steve's group mentoring program to accelerate software developer careers, check out [devBetter](https://devbetter.com). 34 | -------------------------------------------------------------------------------- /src/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | // Use IntelliSense to find out which attributes exist for C# debugging 6 | // Use hover for the description of the existing attributes 7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/M2/after/Interfaces/bin/Debug/net5.0/Interfaces.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/M2/after/Interfaces", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach" 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /src/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/M2/after/Interfaces/Interfaces.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/M2/after/Interfaces/Interfaces.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/M2/after/Interfaces/Interfaces.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /src/M2.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/CSharpGenerics/9c982ad3781737aba6c3f1e583ae2aa6d360840a/src/M2.zip -------------------------------------------------------------------------------- /src/M2/after/Interfaces/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | 5 | { 6 | // Use IntelliSense to find out which attributes exist for C# debugging 7 | // Use hover for the description of the existing attributes 8 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 9 | "name": ".NET Core Launch (console)", 10 | "type": "coreclr", 11 | "request": "launch", 12 | "preLaunchTask": "build", 13 | // If you have changed target frameworks, make sure to update the program path. 14 | "program": "${workspaceFolder}/bin/Debug/net5.0/Interfaces.dll", 15 | "args": [], 16 | "cwd": "${workspaceFolder}", 17 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 18 | "console": "internalConsole", 19 | "stopAtEntry": false, 20 | "logging": { 21 | "moduleLoad": false 22 | } 23 | }, 24 | { 25 | "name": ".NET Core Attach", 26 | "type": "coreclr", 27 | "request": "attach", 28 | "processId": "${command:pickProcess}" 29 | } 30 | ] 31 | } -------------------------------------------------------------------------------- /src/M2/after/Interfaces/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/Interfaces.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/Interfaces.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/Interfaces.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /src/M2/after/Interfaces/Constraints.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public interface IFactory where T : new() 4 | { 5 | T Create(); 6 | } 7 | 8 | interface IStructList where T : struct { } 9 | interface IClassList where T : class { } 10 | interface INullableClassList where T : class? { } 11 | interface INonNullList where T : notnull { } 12 | interface IClassFactory where T : class, new() { } 13 | 14 | public class BaseEntity { } 15 | public class BaseEntity where TId : struct 16 | { 17 | public TId Id { get; private set; } 18 | } 19 | public interface IEntity { } 20 | interface IRepository1 where T : BaseEntity { } // a specific base class 21 | interface IRepository2 where T : BaseEntity? { } 22 | interface IRepository3 where T : IEntity { } 23 | interface IRepository4 where T : IEntity? { } 24 | 25 | interface IRepository where TEntity : BaseEntity 26 | where TId : struct 27 | { 28 | TEntity GetById(TId id); 29 | } 30 | 31 | public class Foo : BaseEntity { } 32 | public class Bar : BaseEntity { } -------------------------------------------------------------------------------- /src/M2/after/Interfaces/Interfaces.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/M2/after/Interfaces/Interfaces.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31205.134 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Interfaces", "Interfaces.csproj", "{DC639180-73FF-4DAC-BD1B-A53C7598A8DE}" 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 | {DC639180-73FF-4DAC-BD1B-A53C7598A8DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {DC639180-73FF-4DAC-BD1B-A53C7598A8DE}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {DC639180-73FF-4DAC-BD1B-A53C7598A8DE}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {DC639180-73FF-4DAC-BD1B-A53C7598A8DE}.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 = {0432E1AB-B589-4750-85C2-EBC9B6478E8A} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /src/M2/after/Interfaces/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace Interfaces 6 | { 7 | class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | Console.WriteLine("Hello World!"); 12 | 13 | var studentService = new StudentPrinterService(new StudentRepository()); 14 | studentService.PrintStudents(5); 15 | 16 | Console.WriteLine(); 17 | 18 | // var authorService = new AuthorPrinterService(new AuthorRepository()); 19 | // authorService.PrintAuthors(); 20 | } 21 | } 22 | 23 | public interface IRepository where T : IComparable 24 | { 25 | IEnumerable List(); 26 | IEnumerable SortedList(); 27 | 28 | } 29 | 30 | public interface IPersonRepository : IRepository where T : Person, IComparable, new() 31 | { 32 | IEnumerable Search(string name); 33 | T Create(Name name); 34 | T CreateDefault(); 35 | } 36 | 37 | public interface IPersonRepository 38 | { 39 | IEnumerable Search(string name) where T : Person; 40 | T Create(Name name) where T : Person; 41 | T CreateDefault() where T : Person, new(); 42 | } 43 | 44 | public class StudentPrinterService 45 | { 46 | private readonly IPersonRepository _studentRepository; 47 | public StudentPrinterService(IPersonRepository studentRepository) 48 | { 49 | _studentRepository = studentRepository; 50 | } 51 | 52 | public void PrintStudents(int max = 100) 53 | { 54 | var students = _studentRepository.SortedList() 55 | .Take(max) 56 | .ToArray(); 57 | 58 | PrintStudentsToConsole(students); 59 | 60 | var smiths = _studentRepository.Search("Smith"); 61 | PrintSmithsToConsole(smiths); 62 | } 63 | 64 | private void PrintStudentsToConsole(IEnumerable students) 65 | { 66 | Console.WriteLine("Students:"); 67 | foreach (var student in students) 68 | { 69 | Console.WriteLine(student); 70 | } 71 | } 72 | private void PrintSmithsToConsole(IEnumerable students) 73 | { 74 | Console.WriteLine("Smiths:"); 75 | foreach (var student in students) 76 | { 77 | Console.WriteLine(student); 78 | } 79 | } 80 | } 81 | 82 | public record Name(string First, string Last); 83 | 84 | public class StudentRepository : IPersonRepository 85 | { 86 | private Name[] _names = new Name[10]; 87 | 88 | public StudentRepository() 89 | { 90 | _names[0] = new("Steve", "Smith"); 91 | _names[1] = new("Chad", "Smith"); 92 | _names[2] = new("Ben", "Smith"); 93 | _names[3] = new("Eric", "Smith"); 94 | _names[4] = new("Julie", "Lerman"); 95 | _names[5] = new("David", "Starr"); 96 | _names[6] = new("Aaron", "Skonnard"); 97 | _names[7] = new("Aaron", "Stewart"); 98 | _names[8] = new("Aaron", "Powell"); 99 | _names[9] = new("Aaron", "Frost"); 100 | } 101 | 102 | public Student Create(Name name) 103 | { 104 | return new Student(name.First, name.Last); 105 | } 106 | 107 | public Student CreateDefault() 108 | { 109 | return new Student(); 110 | } 111 | 112 | public IEnumerable List() 113 | { 114 | int index = 0; 115 | while (index < _names.Length) 116 | { 117 | yield return new Student(_names[index].First, _names[index].Last); 118 | index++; 119 | } 120 | } 121 | 122 | public IEnumerable Search(string name) 123 | { 124 | return List().Where(student => student.FirstName.Contains(name) || 125 | student.LastName.Contains(name)); 126 | } 127 | 128 | public IEnumerable SortedList() 129 | { 130 | var students = List().ToList(); 131 | students.Sort(); 132 | return students; 133 | } 134 | } 135 | 136 | public abstract class Person 137 | { 138 | public string FirstName { get; set; } 139 | public string LastName { get; set; } 140 | } 141 | 142 | public class Student : Person, IComparable 143 | { 144 | public Student(string firstName, string lastName) 145 | { 146 | FirstName = firstName; 147 | LastName = lastName; 148 | } 149 | 150 | public Student() : this("FirstName", "LastName") 151 | { 152 | } 153 | 154 | public override string ToString() 155 | { 156 | return $"{FirstName} {LastName}"; 157 | } 158 | 159 | public int CompareTo(Student other) 160 | { 161 | if (other is null) return 1; 162 | if (other.LastName == this.LastName) 163 | { 164 | return this.FirstName.CompareTo(other.FirstName); 165 | } 166 | return this.LastName.CompareTo(other.LastName); 167 | } 168 | } 169 | 170 | public class AuthorPrinterService 171 | { 172 | private readonly IRepository _authorRepository; 173 | 174 | public AuthorPrinterService(IRepository authorRepository) 175 | { 176 | _authorRepository = authorRepository; 177 | } 178 | 179 | public void PrintAuthors() 180 | { 181 | var authors = _authorRepository.List().ToArray(); 182 | 183 | // sort 184 | Array.Sort(authors); 185 | 186 | Console.WriteLine("Authors:"); 187 | for (int i = 0; i < authors.Length; i++) 188 | { 189 | Console.WriteLine(authors[i]); 190 | } 191 | } 192 | } 193 | 194 | public class AuthorRepository : IRepository 195 | { 196 | public IEnumerable List() 197 | { 198 | // create a bunch of authors 199 | var authors = new Author[10]; 200 | authors[0] = new Author("Steve", "Smith"); 201 | authors[1] = new Author("Chad", "Smith"); 202 | authors[2] = new Author("Ben", "Smith"); 203 | authors[3] = new Author("Eric", "Smith"); 204 | authors[4] = new Author("Julie", "Lerman"); 205 | authors[5] = new Author("David", "Starr"); 206 | authors[6] = new Author("Aaron", "Skonnard"); 207 | authors[7] = new Author("Aaron", "Stewart"); 208 | authors[8] = new Author("Aaron", "Powell"); 209 | authors[9] = new Author("Aaron", "Frost"); 210 | return authors; 211 | } 212 | 213 | public IEnumerable SortedList() 214 | { 215 | throw new NotImplementedException(); 216 | } 217 | } 218 | 219 | public class Author : Person, IComparable 220 | { 221 | public Author(string firstName, string lastName) 222 | { 223 | FirstName = firstName; 224 | LastName = lastName; 225 | } 226 | 227 | public int CompareTo(object obj) 228 | { 229 | if (obj is null) return 1; 230 | 231 | if (obj is Author otherAuthor) 232 | { 233 | return this.ToString().CompareTo(otherAuthor.ToString()); 234 | } 235 | throw new ArgumentException("Not an Author", nameof(obj)); 236 | } 237 | 238 | public override string ToString() 239 | { 240 | return $"{FirstName} {LastName}"; 241 | } 242 | 243 | public int CompareTo(Author other) 244 | { 245 | if (other is null) return 1; 246 | 247 | return this.ToString().CompareTo(other.ToString()); 248 | } 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /src/M2/after/WithoutGenerics/Inbox.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WithoutGenerics 4 | { 5 | public class Inbox 6 | { 7 | public void ListContents(Stack stack) 8 | { 9 | Memo memo = (Memo)stack.Pop(); 10 | while (memo != null) 11 | { 12 | Print(memo.Contents); 13 | memo = (Memo)stack.Pop(); 14 | } 15 | } 16 | 17 | private void Print(string input) 18 | { 19 | Console.WriteLine(input); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/M2/after/WithoutGenerics/Memo.cs: -------------------------------------------------------------------------------- 1 | namespace WithoutGenerics 2 | { 3 | public class Memo 4 | { 5 | public string Contents { get; set; } 6 | } 7 | } -------------------------------------------------------------------------------- /src/M2/after/WithoutGenerics/MemoStack.cs: -------------------------------------------------------------------------------- 1 | namespace WithoutGenerics 2 | { 3 | public class MemoStack 4 | { 5 | private MemoStackItem _top = null; 6 | 7 | public void Push(Memo memo) 8 | { 9 | var item = new MemoStackItem(_top, memo); 10 | _top = item; 11 | } 12 | 13 | public Memo Pop() 14 | { 15 | if (_top is null) return null; 16 | var val = _top.Value; 17 | _top = _top.NextItem; 18 | return val; 19 | } 20 | 21 | private class MemoStackItem 22 | { 23 | public MemoStackItem NextItem { get; private set; } 24 | public Memo Value { get; private set; } 25 | 26 | public MemoStackItem(MemoStackItem nextItem, Memo value) 27 | { 28 | NextItem = nextItem; 29 | Value = value; 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/M2/after/WithoutGenerics/Program.cs: -------------------------------------------------------------------------------- 1 | namespace WithoutGenerics 2 | { 3 | public static class Program 4 | { 5 | public static void Main() 6 | { 7 | var stack = new Stack(); 8 | 9 | stack.Push(new Memo() { Contents = "one"}); 10 | stack.Push(new Memo() { Contents = "two"}); 11 | stack.Push(new Memo() { Contents = "three"}); 12 | 13 | var inbox = new Inbox(); 14 | 15 | inbox.ListContents(stack); // no type safety here - expects stack of Memos 16 | 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/M2/after/WithoutGenerics/Stack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WithoutGenerics 4 | { 5 | public class Stack 6 | { 7 | private StackItem _top = null; 8 | 9 | public void Push(object obj) 10 | { 11 | var item = new StackItem(_top, obj); 12 | _top = item; 13 | } 14 | 15 | public Object Pop() 16 | { 17 | if (_top is null) return null; 18 | var val = _top.Value; 19 | _top = _top.NextItem; 20 | return val; 21 | } 22 | 23 | private class StackItem 24 | { 25 | public StackItem NextItem { get; private set; } 26 | public object Value { get; private set; } 27 | 28 | public StackItem(StackItem nextItem, object value) 29 | { 30 | NextItem = nextItem; 31 | Value = value; 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/M2/after/WithoutGenerics/UnitTests/Stack_Pop.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace WithoutGenerics 4 | { 5 | public class Stack_Pop 6 | { 7 | [Fact] 8 | public void ReturnsNullWhenStackEmpty() 9 | { 10 | var stack = new Stack(); 11 | 12 | var result = stack.Pop(); 13 | 14 | Assert.Null(result); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/M2/after/WithoutGenerics/UnitTests/Stack_Push.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace WithoutGenerics 4 | { 5 | public class Stack_Push 6 | { 7 | [Fact] 8 | public void AddsItemToTopOfStack() 9 | { 10 | var stack = new Stack(); 11 | stack.Push(1); 12 | stack.Push(2); 13 | stack.Push(3); 14 | 15 | var item = (int)stack.Pop(); 16 | 17 | Assert.Equal(3, item); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/M2/after/WithoutGenerics/WithoutGenerics.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | WithoutGenerics.Program 9 | 10 | 11 | 12 | 13 | 14 | 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | all 17 | 18 | 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | all 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/M2/before/README.md: -------------------------------------------------------------------------------- 1 | # Module 2 2 | 3 | Welcome! 4 | 5 | In this module we started from scratch, so there is nothing in this "before" folder. 6 | 7 | You'll find the completed code in the "after" folder. 8 | 9 | Look for the latest code on GitHub: 10 | 11 | https://github.com/ardalis/CSharpGenerics 12 | 13 | Thanks! 14 | 15 | Steve "ardalis" Smith 16 | 17 | Find or Connect with me: 18 | 19 | - [ardalis.com](https://ardalis.com) 20 | - [twitter](https://twitter.com/ardalis) 21 | - [github](https://github.com/ardalis) 22 | - [youtube](https://youtube.com/ardalis) 23 | - [mentoring and coaching](https://nimblepros.com) 24 | - [linkedin](https://www.linkedin.com/in/stevenandrewsmith/) 25 | -------------------------------------------------------------------------------- /src/M3/after/ReflectionVariance/ReflectionVariance.ConsoleApp/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | // Use IntelliSense to find out which attributes exist for C# debugging 6 | // Use hover for the description of the existing attributes 7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/bin/Debug/net5.0/ReflectionVariance.ConsoleApp.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false, 19 | "logging": { 20 | "moduleLoad": false 21 | } 22 | }, 23 | { 24 | "name": ".NET Core Attach", 25 | "type": "coreclr", 26 | "request": "attach", 27 | "processId": "${command:pickProcess}" 28 | } 29 | ] 30 | } -------------------------------------------------------------------------------- /src/M3/after/ReflectionVariance/ReflectionVariance.ConsoleApp/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/ReflectionVariance.ConsoleApp.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/ReflectionVariance.ConsoleApp.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/ReflectionVariance.ConsoleApp.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /src/M3/after/ReflectionVariance/ReflectionVariance.ConsoleApp/ContravarianceSamples.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace ReflectionVariance.ConsoleApp 5 | { 6 | // these are just code samples used to create slides 7 | internal class ContravarianceSamples 8 | { 9 | internal static void Execute() 10 | { 11 | var sequence = new MemorySequence(); 12 | 13 | AddPeople(sequence); 14 | AddAuthors(sequence); 15 | 16 | PrintSequence(sequence); 17 | } 18 | 19 | private static void PrintSequence(ISequenceReader sequence) 20 | { 21 | while(true) 22 | { 23 | var currentItem = sequence.GetNextItem(); 24 | if(currentItem == null) break; 25 | Console.WriteLine(currentItem); 26 | } 27 | } 28 | 29 | private static void AddAuthors(ISequenceWriter sequence) 30 | { 31 | sequence.Add(new Author { FirstName = "Steve", LastName = "Smith" }); 32 | } 33 | 34 | private static void AddPeople(ISequenceWriter sequence) 35 | { 36 | sequence.Add(new Person { FirstName = "George", LastName = "Washington" }); 37 | } 38 | 39 | 40 | 41 | 42 | 43 | 44 | class Person 45 | { 46 | public string FirstName { get; set; } 47 | public string LastName { get; set; } 48 | public override string ToString() 49 | { 50 | return $"{FirstName} {LastName}"; 51 | } 52 | } 53 | class Author : Person 54 | { 55 | } 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | interface ISequenceWriter 64 | { 65 | void Add(T item); 66 | } 67 | 68 | interface ISequenceReader 69 | { 70 | T GetNextItem(); 71 | } 72 | 73 | interface ISequence : ISequenceReader, ISequenceWriter { } 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | public class MemorySequence : ISequence 82 | // : ISequenceWriter, ISequenceReader 83 | { 84 | private Queue _queue = new Queue(); 85 | 86 | public void Add(T item) 87 | { 88 | _queue.Enqueue(item); 89 | } 90 | 91 | public T GetNextItem() 92 | { 93 | if(_queue.Count == 0) return default(T); 94 | return _queue.Dequeue(); 95 | } 96 | } 97 | } 98 | } -------------------------------------------------------------------------------- /src/M3/after/ReflectionVariance/ReflectionVariance.ConsoleApp/CovarianceSamples.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ReflectionVariance.ConsoleApp 4 | { 5 | // these are just code samples used to create slides 6 | internal class CovarianceSamples 7 | { 8 | internal static void Execute() 9 | { 10 | var h1 = new Handler(); 11 | var h2 = new Handler(); 12 | 13 | } 14 | 15 | public interface ISequence 16 | { 17 | T GetNext(); 18 | // void Insert(T item); // compile error 19 | } 20 | public interface IHandler 21 | { 22 | void Handle(TCommand command); 23 | } 24 | public class Handler : IHandler 25 | { 26 | public void Handle(TCommand command) 27 | { 28 | } 29 | } 30 | public class BaseCommand { } 31 | public class SpecialCommand : BaseCommand { } 32 | 33 | } 34 | } -------------------------------------------------------------------------------- /src/M3/after/ReflectionVariance/ReflectionVariance.ConsoleApp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ReflectionVariance.ConsoleApp 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | Console.WriteLine("Reflection and Variance with @ardalis!"); 10 | 11 | //ReflectionSamples.Execute(); 12 | 13 | //VarianceSamples.Execute(); 14 | 15 | // CovarianceSamples.Execute(); 16 | ContravarianceSamples.Execute(); 17 | } 18 | } 19 | 20 | public interface IProcessor 21 | { 22 | void Process(T input); 23 | } 24 | public class Processor : IProcessor 25 | { 26 | public void Process(T input) 27 | { 28 | Console.WriteLine($"Generic Processor of T, processing {input}"); 29 | } 30 | } 31 | 32 | public interface ILogger 33 | { 34 | void Log(T input); 35 | } 36 | public record Customer(string firstName, string lastName); 37 | 38 | public class CustomerProcessor : IProcessor, ILogger 39 | { 40 | public void Process(Customer input) 41 | { 42 | Console.WriteLine($"Processing Customer: {input}"); 43 | } 44 | 45 | public static void ExpediteProcess(TExpedited input) 46 | { 47 | Console.WriteLine($">>> EXPEDITE! {input}"); 48 | } 49 | 50 | public void Log(T input) 51 | { 52 | Console.WriteLine($"Logging Generic Type: {input}"); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/M3/after/ReflectionVariance/ReflectionVariance.ConsoleApp/ReflectionSamples.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | namespace ReflectionVariance.ConsoleApp 7 | { 8 | internal class ReflectionSamples 9 | { 10 | internal static void Execute() 11 | { 12 | var types = new List 13 | { 14 | // typeof(IProcessor<>), 15 | // typeof(IProcessor), 16 | // typeof(Processor<>), 17 | // typeof(Processor), 18 | // typeof(CustomerProcessor) 19 | typeof(IPipeline<,>) 20 | }; 21 | ListTypeDetails(types); 22 | 23 | // methods 24 | // var methods = typeof(IProcessor<>).GetMethods(); 25 | 26 | // Create a Pipeline Instance 27 | Type[] typeArguments = { typeof(Request), typeof(Response) }; 28 | 29 | var specificType = typeof(Pipeline<,>).MakeGenericType(typeArguments); 30 | 31 | var createdInstance = Activator.CreateInstance(specificType); 32 | 33 | ListTypeDetails(new List { createdInstance.GetType() }); 34 | 35 | ((dynamic)createdInstance).DoWork(new Request()); 36 | } 37 | 38 | private static void ListTypeDetails(List types) 39 | { 40 | Console.WriteLine("Type Name".PadRight(20) + "|" + "IsGenericType?".PadRight(20) + "|" + 41 | "IsGenericDefinition?".PadRight(20) + "|" + "Generic Arguments"); 42 | foreach (var type in types) 43 | { 44 | string output = type.Name.PadRight(20) + "|"; 45 | output += type.IsGenericType.ToString().PadRight(20) + "|"; 46 | output += type.IsGenericTypeDefinition.ToString().PadRight(20) + "|"; 47 | output += type.GetGenericArguments().Count(); 48 | Console.WriteLine(output); 49 | ListParameterDetails(type); 50 | // ListGenericMethods(type); 51 | // Console.WriteLine(output); 52 | } 53 | } 54 | 55 | private static void ListParameterDetails(Type type) 56 | { 57 | var parameters = type.GetGenericArguments(); 58 | 59 | foreach (var parameter in parameters) 60 | { 61 | if (parameter.IsGenericParameter) 62 | { 63 | DisplayGenericParameter(parameter); 64 | } 65 | else 66 | { 67 | DisplayTypeArgument(parameter); 68 | } 69 | } 70 | } 71 | 72 | private static void DisplayGenericParameter(Type parameter) 73 | { 74 | var constraints = parameter.GetGenericParameterConstraints(); 75 | 76 | Console.WriteLine($" Type parameter (position, name, constraints, attributeMask): {parameter.GenericParameterPosition}, {parameter.Name}, {constraints.Count()}, {parameter.GenericParameterAttributes}"); 77 | 78 | if (constraints.Any()) 79 | { 80 | Console.WriteLine(" Constraint Name |Interface? |Class? |Enum? "); 81 | foreach (var constraint in constraints) 82 | { 83 | Console.WriteLine(" " + constraint.Name.PadRight(16) + "|" + 84 | constraint.IsInterface.ToString().PadRight(11) + "|" + 85 | constraint.IsClass.ToString().PadRight(7) + "|" + 86 | constraint.IsEnum.ToString().PadRight(6) 87 | ); 88 | } 89 | 90 | } 91 | } 92 | 93 | private static void DisplayTypeArgument(Type parameter) 94 | { 95 | Console.WriteLine($" Type argument: {parameter.Name}"); 96 | } 97 | 98 | private static void ListGenericMethods(Type type) 99 | { 100 | var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static) 101 | .Where(method => method.DeclaringType.Name != "Object"); 102 | Console.WriteLine($"Methods of type {type.Name}:"); 103 | Console.WriteLine("Name |IsGeneric |IsGenDefin |ContainsGenParams"); 104 | int colWidth = 12; 105 | foreach (var method in methods) 106 | { 107 | int maxNameLength = Math.Min(method.Name.Length, colWidth); 108 | Console.Write(method.Name.Substring(0, maxNameLength).PadRight(colWidth)); 109 | Console.Write("|"); 110 | Console.Write(method.IsGenericMethod.ToString().PadRight(colWidth)); 111 | Console.Write("|"); 112 | Console.Write(method.IsGenericMethodDefinition.ToString().PadRight(colWidth)); 113 | Console.Write("|"); 114 | Console.WriteLine(method.ContainsGenericParameters.ToString().PadRight(colWidth)); 115 | 116 | if (method.IsGenericMethod) 117 | { 118 | Console.WriteLine("Executing generic method..."); 119 | var genParams = method.GetGenericArguments(); 120 | foreach (var genParam in genParams) 121 | { 122 | if (genParam.IsGenericParameter) 123 | { 124 | Console.WriteLine($"Generic Param: {genParam.GenericParameterPosition} {genParam.Name} "); 125 | } 126 | } 127 | MethodInfo genericMethod = method.MakeGenericMethod(typeof(Customer)); 128 | object instance = null; 129 | if (!genericMethod.IsStatic) 130 | { 131 | instance = Activator.CreateInstance(type); 132 | } 133 | genericMethod.Invoke(instance, new[] { new Customer("Steve", "Smith") }); 134 | } 135 | } 136 | Console.WriteLine(); 137 | } 138 | } 139 | 140 | public interface IHandler { } 141 | public class Handler : IHandler { } 142 | 143 | public class RequestHandler : Handler { } 144 | 145 | public interface IEndpoint 146 | { 147 | TResponse Handle(TRequest request); 148 | } 149 | 150 | public interface IHandler 151 | { 152 | void Handle(TCommand command); 153 | } 154 | public class Handler : IHandler 155 | { 156 | public void Handle(TCommand command) 157 | { 158 | } 159 | } 160 | public class BaseCommand { } 161 | public class SpecialCommand : BaseCommand { } 162 | 163 | public abstract class BaseRequest { } 164 | public interface IPipeline 165 | where TInput : BaseRequest 166 | where TOutput : IDisposable, new() 167 | { 168 | TOutput DoWork(TInput request); 169 | } 170 | 171 | public class Pipeline : IPipeline 172 | where TInput : BaseRequest 173 | where TOutput : IDisposable, new() 174 | { 175 | public TOutput DoWork(TInput request) 176 | { 177 | var response = new TOutput(); 178 | Console.WriteLine($"Got request : {request}; returning response: {response}"); 179 | return response; 180 | } 181 | } 182 | 183 | 184 | public class Request : BaseRequest { } 185 | public class Response : IDisposable 186 | { 187 | public void Dispose() 188 | { 189 | } 190 | } 191 | 192 | 193 | } -------------------------------------------------------------------------------- /src/M3/after/ReflectionVariance/ReflectionVariance.ConsoleApp/ReflectionVariance.ConsoleApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/M3/after/ReflectionVariance/ReflectionVariance.ConsoleApp/VarianceSamples.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ReflectionVariance.ConsoleApp 4 | { 5 | internal class VarianceSamples 6 | { 7 | public static void Execute() 8 | { 9 | Console.WriteLine("Variance in C# types and generic types:"); 10 | 11 | var handler = new Handler(); 12 | var requestHandler = new RequestHandler(); 13 | Console.WriteLine($"handler instance is IHandler: {handler is IHandler}"); 14 | Console.WriteLine($"handler instance is Object: {handler is Object}"); 15 | Console.WriteLine($"handler instance is Handler: {handler is Handler}"); 16 | Console.WriteLine($"handler instance is RequestHandler: {handler is RequestHandler}"); 17 | Console.WriteLine(); 18 | Console.WriteLine($"requestHandler instance is IHandler: {requestHandler is IHandler}"); 19 | Console.WriteLine($"requestHandler instance is Object: {requestHandler is Object}"); 20 | Console.WriteLine($"requestHandler instance is Handler: {requestHandler is Handler}"); 21 | Console.WriteLine($"requestHandler instance is RequestHandler: {requestHandler is RequestHandler}"); 22 | 23 | Console.WriteLine(); 24 | 25 | // assignment to less specific type 26 | Handler handler2 = handler; 27 | handler2 = requestHandler; 28 | 29 | // assignment to more specific type 30 | RequestHandler requestHandler2 = requestHandler; 31 | //requestHandler2 = handler; // compile error - cannot implicitly convert 32 | //requestHandler2 = (RequestHandler)handler; // runtime error - cannot cast 33 | 34 | 35 | // Method1 36 | Method1(handler); 37 | Console.WriteLine("Can we pass handler to Method1? Yes."); 38 | 39 | Method1(requestHandler); 40 | Console.WriteLine("Can we pass requestHandler to Method1? Yes."); 41 | 42 | // Method2 43 | //Method2(handler); // Cannot convert 44 | Console.WriteLine("Can we pass handler to Method2? NO."); 45 | 46 | Method2(requestHandler); 47 | Console.WriteLine("Can we pass requestHandler to Method2? Yes."); 48 | 49 | // Method3 50 | handler = Method3(); 51 | //requestHandler = Method3(); // Cannot convert H to RH 52 | handler = Method4(); 53 | requestHandler = Method4(); 54 | 55 | // Generic interfaces 56 | var h1 = new Handler(); 57 | var h2 = new Handler(); 58 | 59 | ProcessBase(h1); 60 | //ProcessBase(h2); // cannot convert 61 | //ProcessSpecial(h1); // cannot convert 62 | ProcessSpecial(h2); 63 | } 64 | 65 | public static void Method1(Handler handler) 66 | { 67 | } 68 | public static void Method2(RequestHandler handler) 69 | { 70 | } 71 | public static Handler Method3() { return null; } 72 | public static RequestHandler Method4() { return null; } 73 | public static void ProcessBase(IHandler handler) { } 74 | public static void ProcessSpecial(IHandler handler) { } 75 | 76 | } 77 | } -------------------------------------------------------------------------------- /src/M3/after/ReflectionVariance/ReflectionVariance.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31205.134 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ReflectionVariance.ConsoleApp", "ReflectionVariance.ConsoleApp\ReflectionVariance.ConsoleApp.csproj", "{43128C0D-E2BD-479D-AB6E-ADB067E318A2}" 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 | {43128C0D-E2BD-479D-AB6E-ADB067E318A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {43128C0D-E2BD-479D-AB6E-ADB067E318A2}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {43128C0D-E2BD-479D-AB6E-ADB067E318A2}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {43128C0D-E2BD-479D-AB6E-ADB067E318A2}.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 = {6CE8793E-ADDE-4829-BE9A-7C1333550D10} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /src/M3/before/README.md: -------------------------------------------------------------------------------- 1 | # Module 2 2 | 3 | Welcome! 4 | 5 | In this module we started from scratch, so there is nothing in this "before" folder. 6 | 7 | You'll find the completed code in the "after" folder. 8 | 9 | Look for the latest code on GitHub: 10 | 11 | https://github.com/ardalis/CSharpGenerics 12 | 13 | Thanks! 14 | 15 | Steve "ardalis" Smith 16 | 17 | Find or Connect with me: 18 | 19 | - [ardalis.com](https://ardalis.com) 20 | - [twitter](https://twitter.com/ardalis) 21 | - [github](https://github.com/ardalis) 22 | - [youtube](https://youtube.com/ardalis) 23 | - [mentoring and coaching](https://nimblepros.com) 24 | - [linkedin](https://www.linkedin.com/in/stevenandrewsmith/) 25 | -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | "program": "${workspaceFolder}/bin/Debug/net5.0/ClassesMethods.dll", 13 | "args": [], 14 | "cwd": "${workspaceFolder}", 15 | "console": "internalConsole", 16 | "stopAtEntry": false 17 | }, 18 | { 19 | "name": ".NET Core Attach", 20 | "type": "coreclr", 21 | "request": "attach" 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/ClassesMethods.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/ClassesMethods.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/ClassesMethods.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/BasicDefinitions.cs: -------------------------------------------------------------------------------- 1 | namespace BasicDefinitions 2 | { 3 | // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-classes 4 | 5 | class BaseResult { } 6 | class BaseResultGeneric { } 7 | 8 | // generic inherit from concrete type (aka non-generic) 9 | class ResultFromConcrete : BaseResult { } 10 | 11 | // generic inherit from closed constructed type 12 | class ResultFromClosed : BaseResultGeneric { } 13 | 14 | // generic inherit from open constructed type 15 | class ResultFromOpen : BaseResultGeneric { } 16 | 17 | // concrete inherit from closed constructed type 18 | class IntResult : BaseResultGeneric { } 19 | 20 | // concrete cannot inherit from open constructed class 21 | //class Result2 : BaseResultGeneric {} // ERROR 22 | 23 | // concrete cannot inherit simply from T 24 | //class Result3 : T {} // ERROR 25 | 26 | class BaseResultMultiple { } 27 | 28 | // Single-variable generic can inherit from multi-variable if some types are closed 29 | class IntResult4 : BaseResultMultiple { } 30 | 31 | // Closed constructed types(in this case int) can't be set on the derived type 32 | //class IntResult5 : BaseResultGeneric {} // ERROR 33 | 34 | // Multi-generic class can inherit from multi-generic class as long as all types are defined 35 | class MultiResult5 : BaseResultMultiple { } 36 | 37 | // Leaving undefined generic types on base and not on defined class produces an error 38 | //class Result6 : BaseResultMultiple {} // ERROR 39 | } -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/Cache.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace CodeProjectCache 5 | { 6 | // Cache 7 | // Original source (with more features and better safety) 8 | // https://www.codeproject.com/Articles/1033606/Cache-T-A-threadsafe-Simple-Efficient-Generic-In-m 9 | 10 | public class Cache // TODO: IDisposable 11 | { 12 | private Dictionary _cache = new(); 13 | // omitted: timers and locking. See original source for real code 14 | 15 | public void AddOrUpdate(TKey key, TObject itemToCache) 16 | { 17 | if (_cache.ContainsKey(key)) 18 | { 19 | _cache[key] = itemToCache; 20 | } 21 | else 22 | { 23 | _cache.Add(key, itemToCache); 24 | } 25 | } 26 | 27 | public TObject Get(TKey key) 28 | { 29 | if (_cache.ContainsKey(key)) 30 | { 31 | return _cache[key]; 32 | } 33 | return default(TObject); 34 | } 35 | } 36 | 37 | // non-generic class inherits from generic 38 | // can have as many instances as desired, or use a global one 39 | public class Cache : Cache 40 | { 41 | private static Lazy _globalCache = new Lazy(); 42 | public static Cache Global => _globalCache.Value; // simple Singleton pattern 43 | } 44 | } -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/ClassesMethods.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/Commands.cs: -------------------------------------------------------------------------------- 1 | // Sample from https://stackoverflow.com/a/52884586/13729 2 | using System; 3 | using System.Collections.Generic; 4 | using Ardalis.GuardClauses; 5 | 6 | namespace Generic.Commands 7 | { 8 | public interface ICommand 9 | { 10 | object Execute(); 11 | } 12 | 13 | public interface ICommand : ICommand 14 | { 15 | new TResult Execute(); 16 | } 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | // concrete Command class implements non-generic interface 29 | public class Command : ICommand 30 | { 31 | protected Func ExecFunc { get; } 32 | 33 | public object Execute() 34 | { 35 | return ExecFunc(this); 36 | } 37 | 38 | public Command(Func execFunc) 39 | { 40 | ExecFunc = Guard.Against.Null(execFunc, nameof(execFunc)); 41 | } 42 | } 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | // generic class inherits from non-generic 51 | public class Command : Command, ICommand where TResult : class 52 | { 53 | new protected Func, TResult> ExecFunc => (ICommand cmd) => (TResult)base.ExecFunc(cmd); 54 | 55 | TResult ICommand.Execute() 56 | { 57 | return ExecFunc(this); 58 | } 59 | 60 | public Command(Func, TResult> execFunc) : 61 | base((ICommand c) => (object)execFunc((ICommand)c)) 62 | { 63 | } 64 | } 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | public class ConcatCommand : Command 73 | { 74 | public IEnumerable Inputs { get; } 75 | 76 | public ConcatCommand(IEnumerable inputs) : 77 | base((ICommand c) => (string)String.Concat(((ConcatCommand)c).Inputs)) 78 | { 79 | Inputs = Guard.Against.Null(inputs, nameof(inputs)); 80 | } 81 | } 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | public class CollectCommand : Command 94 | { 95 | public IEnumerable Inputs { get; } 96 | public CollectCommand(IEnumerable inputs) : 97 | base((ICommand c) => new List(((CollectCommand)c).Inputs)) 98 | { 99 | Inputs = Guard.Against.Null(inputs, nameof(inputs)); 100 | } 101 | } 102 | } -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/Complexity.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Complexity 4 | { 5 | class Category {} 6 | class Author {} 7 | class Course {} 8 | 9 | class Sample 10 | { 11 | static void Run() 12 | { 13 | var catalog = new Dictionary>>(); 14 | var courseCatalog = new CourseCatalog(); 15 | } 16 | } 17 | 18 | class CourseCatalog : Dictionary>> 19 | { 20 | // custom business logic here 21 | } 22 | } -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/Counter.cs: -------------------------------------------------------------------------------- 1 | namespace Counter 2 | { 3 | // these examples are not threadsafe 4 | public class BaseClass 5 | { 6 | public static int GlobalCounter { get; set; } 7 | public int LocalCounter { get; set; } 8 | } 9 | public class Generic : BaseClass 10 | { 11 | public static int Counter { get; set; } 12 | public int AnotherCounter 13 | { 14 | get { return BaseClass.GlobalCounter; } 15 | set { BaseClass.GlobalCounter = value; } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace ClassesMethods 6 | { 7 | // extension methods 8 | public static class GenericExtensions 9 | { 10 | // confirm a sequence is not empty 11 | public static bool WhereNotEmpty(this IEnumerable source) 12 | { 13 | return source.Any(); // LINQ is basically a collection of these kinds of methods 14 | } 15 | 16 | // see if any instance is its default 17 | public static bool IsDefault(this T input) where T : IEquatable 18 | { 19 | return input.Equals(default(T)); 20 | } 21 | 22 | public static T Default(this T input) 23 | { 24 | return default(T); 25 | } 26 | 27 | // swap any struct type with another of the same type 28 | public static void Swap(this ref T input, ref T other) where T : struct 29 | { 30 | T temporary = input; 31 | input = other; 32 | other = temporary; 33 | } 34 | 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/FluentGenerics.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace FluentGenerics 4 | { 5 | class Process 6 | { 7 | void Execute() { } 8 | } 9 | class Process 10 | { 11 | TOut Execute(TIn input) 12 | { 13 | return default(TOut); 14 | } 15 | } 16 | class Process 17 | { 18 | void Execute(TIn input) { } 19 | } 20 | 21 | // can't compile due to conflict with Process 22 | // class Process 23 | // { 24 | // TOut Execute() 25 | // { 26 | // return default(TOut); 27 | // } 28 | // } 29 | 30 | public static class FluentProcess 31 | { 32 | public static class WithInput 33 | { 34 | public abstract class WithOutput 35 | { 36 | public abstract TOut Execute(TIn input); 37 | } 38 | public abstract class WithoutOutput 39 | { 40 | public abstract void Execute(TIn input); 41 | } 42 | } 43 | public static class WithoutInput 44 | { 45 | public abstract class WithOutput 46 | { 47 | public abstract TOut Execute(); 48 | } 49 | public abstract class WithoutOutput 50 | { 51 | public abstract void Execute(); 52 | } 53 | } 54 | } 55 | 56 | 57 | // usage 58 | class TranslateXToY : FluentProcess 59 | .WithInput 60 | .WithOutput 61 | { 62 | public override string Execute(string input) 63 | { 64 | throw new System.NotImplementedException(); 65 | } 66 | } 67 | 68 | class ListItems : FluentProcess 69 | .WithoutInput 70 | .WithOutput> 71 | { 72 | public override IEnumerable Execute() 73 | { 74 | throw new System.NotImplementedException(); 75 | } 76 | } 77 | 78 | class DeleteItem : FluentProcess 79 | .WithInput 80 | .WithoutOutput 81 | { 82 | public override void Execute(int input) 83 | { 84 | throw new System.NotImplementedException(); 85 | } 86 | } 87 | 88 | class ResetAllData : FluentProcess 89 | .WithoutInput 90 | .WithoutOutput 91 | { 92 | public override void Execute() 93 | { 94 | throw new System.NotImplementedException(); 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/GenericStatic.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | 5 | namespace ClassesMethods 6 | { 7 | // https://stackoverflow.com/a/2686133/13729 8 | // better type inference 9 | public static class Converter 10 | { 11 | public static TOut Convert(TIn input) where TOut : class 12 | { 13 | return null; 14 | } 15 | } 16 | 17 | public static class ConvertTo where TOut : class 18 | { 19 | public static TOut Convert(TIn input) 20 | { 21 | return null; 22 | } 23 | } 24 | 25 | 26 | 27 | // generic static classes 28 | public abstract class BaseEntity { }; 29 | public class Customer : BaseEntity { } 30 | public static class DataAccess where T : BaseEntity 31 | { 32 | public static IEnumerable List() 33 | { 34 | return new List(); 35 | } 36 | } 37 | 38 | public interface IDataAccess 39 | { 40 | IEnumerable List(); 41 | } 42 | 43 | // generic constructors 44 | // this is ok - referencing a generic *in* a constructor 45 | public class Repository where TEntity : BaseEntity 46 | where TDataAccess : IDataAccess 47 | { 48 | private TDataAccess _dataAccess; 49 | public Repository(TDataAccess dataAccess) 50 | { 51 | _dataAccess = dataAccess; 52 | } 53 | 54 | public IEnumerable List() 55 | { 56 | return (IEnumerable)_dataAccess.List(); 57 | } 58 | } 59 | 60 | // generic constructor 61 | // this isn't allowed - won't compile 62 | public class Handler 63 | { 64 | // public Handler(Func func) 65 | // { 66 | // // execute func as part of construction 67 | // } 68 | 69 | public static Handler CreateWithFunc(Func func) 70 | { 71 | return new Handler(func); 72 | } 73 | } 74 | public class Handler 75 | { 76 | private readonly Func _func; 77 | 78 | public Handler(Func func) 79 | { 80 | _func = func; 81 | } 82 | } 83 | 84 | // sample from https://stackoverflow.com/a/700986/13729 85 | public interface IGenericType 86 | { 87 | } 88 | 89 | public static class Foo 90 | { 91 | public static Foo Create(IGenericType instance) 92 | { 93 | return new Foo(instance); 94 | } 95 | } 96 | public class Foo 97 | { 98 | public Foo(IGenericType instance) 99 | { 100 | 101 | } 102 | } 103 | 104 | public class SampleUsage 105 | { 106 | static void Execute() 107 | { 108 | // no inference 109 | Handler h = new Handler(a => a * a); 110 | //Handler h2 = Handler.CreateWithFunc(a => a * a); // no type inference 111 | } 112 | } 113 | 114 | 115 | // compile warning 116 | class GenericClass 117 | { 118 | void GenericMethod() {} 119 | } 120 | } -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using BasicDefinitions; 5 | using CodeProjectCache; 6 | using Counter; 7 | using Generic.Commands; 8 | 9 | namespace ClassesMethods 10 | { 11 | class Program 12 | { 13 | static void Main(string[] args) 14 | { 15 | Console.WriteLine("Generic Classes and Methods"); 16 | 17 | // basics 18 | var r = new ResultFromClosed(); // T is string even though its base class T is int 19 | 20 | 21 | // non-static generic classes 22 | // cache 23 | // string message = "Generics are fun!"; 24 | // var cache = new Cache(); // per instance (thus per key/value type combination) 25 | // string key = "fun-message"; 26 | // cache.AddOrUpdate(key, message); 27 | // string cachedResult = cache.Get(key); 28 | // Console.WriteLine(cachedResult); 29 | 30 | // string message2 = "Lazy loading is fun, too."; 31 | // string message2key = "lazy-message"; 32 | // Cache.Global.AddOrUpdate(message2key, message2); // essentially as singleton 33 | // object cachedResult2 = Cache.Global.Get(message2key); // note: no strong typing 34 | // Console.WriteLine(cachedResult2); 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | // working with generics that have a generic base class and non-generic analogs 45 | string[] inputs = { "Follow ", "Steve ", "on ", "Pluralsight.com ", "to ", "get ", "updates!" }; 46 | ICommand c = new ConcatCommand(inputs); // can replace with ICommand 47 | string results = c.Execute(); // which eliminates the cast here 48 | Console.WriteLine(results); 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | // counters -- these are not threadsafe 62 | BaseClass.GlobalCounter += 10; 63 | Generic.Counter += 5; 64 | Generic.Counter += 7; 65 | 66 | Console.WriteLine($"Counts: {BaseClass.GlobalCounter} {Generic.Counter} {Generic.Counter}"); 67 | 68 | Generic.GlobalCounter += 5; 69 | Generic.GlobalCounter += 5; 70 | Console.WriteLine($"Counts: {BaseClass.GlobalCounter} {Generic.Counter} {Generic.Counter}"); 71 | 72 | var intInstance = new Generic(); 73 | intInstance.AnotherCounter++; 74 | Console.WriteLine($"Counts: {BaseClass.GlobalCounter} {Generic.Counter} {Generic.Counter}"); 75 | intInstance.LocalCounter++; 76 | var stringInstance = new Generic(); 77 | stringInstance.LocalCounter++; 78 | Console.WriteLine($"Counts: int: {intInstance.LocalCounter} string: {stringInstance.LocalCounter}"); 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | // using the non-generic command with just objects 87 | var stuff = new Object[] { 1, "hey", 4.3 }; 88 | var collectCommand = new CollectCommand(stuff); 89 | var collectResult = (List)collectCommand.Execute(); 90 | // Console.WriteLine(String.Join(',', collectResult 91 | // .Select(o => o.ToString()).ToArray())); 92 | 93 | 94 | // static classes/methods 95 | //string result = Converter.Convert("input"); // type arguments cannot be inferred 96 | string result0 = Converter.Convert("input"); // must specify every type 97 | string result = ConvertTo.Convert("input"); // only need to specify output type 98 | 99 | 100 | 101 | 102 | 103 | 104 | // extension methods -- cover in methods section 105 | string someMessage = ""; 106 | Console.WriteLine($"Is message not empty? {someMessage.ToArray().WhereNotEmpty()}"); 107 | Console.WriteLine($"Is message default? {someMessage.IsDefault()}"); 108 | Console.WriteLine($"Is 0 default? {0.IsDefault()}"); 109 | 110 | // swap - extension method 111 | int a = 1; 112 | int b = 2; 113 | a.Swap(ref b); // specify type 114 | Console.WriteLine($"a: {a},b: {b}"); 115 | a.Swap(ref b); // type inferred by argument 116 | // a and b should be back to original values 117 | Console.WriteLine($"a: {a},b: {b}"); 118 | 119 | // swap strings 120 | string one = "one"; 121 | string two = "two"; 122 | // one.Swap(ref two); // Error - not a struct 123 | 124 | 125 | // static data access - not recommended typically 126 | IEnumerable customers = DataAccess.List(); 127 | 128 | } 129 | 130 | public static void Swap(ref T a, ref T b) 131 | { 132 | T temp = a; 133 | a = b; 134 | b = temp; 135 | } 136 | } 137 | 138 | 139 | 140 | 141 | } 142 | -------------------------------------------------------------------------------- /src/M4/after/ClassesMethods/Repositories.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | 5 | namespace Repositories 6 | { 7 | public class BaseEntity { } 8 | public interface IAggregateRoot { } 9 | public class Customer : BaseEntity, IAggregateRoot 10 | { 11 | internal void Add(Order order) 12 | { 13 | throw new NotImplementedException(); 14 | } 15 | } 16 | public class Order : BaseEntity, IAggregateRoot { } 17 | public interface ISpecification { } // see Ardalis.Specification nuget package 18 | 19 | public interface IRepository 20 | { 21 | Task GetByIdAsync(int id) where T : BaseEntity, IAggregateRoot; 22 | Task> ListAsync() where T : BaseEntity, IAggregateRoot; 23 | Task> ListAsync(ISpecification spec) where T : BaseEntity, IAggregateRoot; 24 | Task AddAsync(T entity) where T : BaseEntity, IAggregateRoot; 25 | Task UpdateAsync(T entity) where T : BaseEntity, IAggregateRoot; 26 | Task DeleteAsync(T entity) where T : BaseEntity, IAggregateRoot; 27 | } 28 | 29 | public class SomeController 30 | { 31 | private readonly IRepository _repo; 32 | 33 | public SomeController(IRepository repo) 34 | { 35 | _repo = repo; 36 | } 37 | 38 | public async Task> ListCustomers() 39 | { 40 | return await _repo.ListAsync(); 41 | } 42 | public async Task> ListOrders() 43 | { 44 | return await _repo.ListAsync(); 45 | } 46 | 47 | public async Task AddOrderToCustomer(int orderId, int customerId) 48 | { 49 | var order = await _repo.GetByIdAsync(orderId); 50 | var customer = await _repo.GetByIdAsync(customerId); 51 | customer.Add(order); 52 | await _repo.UpdateAsync(customer); // type inferred 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /src/M5/after/EventsDelegates/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | "program": "${workspaceFolder}/bin/Debug/net5.0/EventsDelegates.dll", 13 | "args": [], 14 | "cwd": "${workspaceFolder}", 15 | "console": "internalConsole", 16 | "stopAtEntry": false 17 | }, 18 | { 19 | "name": ".NET Core Attach", 20 | "type": "coreclr", 21 | "request": "attach" 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /src/M5/after/EventsDelegates/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/EventsDelegates.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/EventsDelegates.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/EventsDelegates.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /src/M5/after/EventsDelegates/BaseRepositories.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace BaseRepositories 5 | { 6 | public interface IWriteRepository 7 | { 8 | void Add(T entity); 9 | event EventHandler> EntityAdded; 10 | } 11 | 12 | // using an EventArgs type makes design more extensible 13 | public class EntityAddedEventArgs : EventArgs 14 | { 15 | public EntityAddedEventArgs(T entityAdded) 16 | { 17 | EntityAdded = entityAdded; 18 | } 19 | 20 | public T EntityAdded { get; } 21 | } 22 | 23 | 24 | 25 | public abstract class RepositoryBase : IWriteRepository 26 | { 27 | public event EventHandler> EntityAdded; 28 | 29 | // derived classes need to remember to call OnEntityAdded() 30 | public abstract void Add(T entity); 31 | 32 | protected virtual void OnEntityAdded(EntityAddedEventArgs eventArgs) 33 | { 34 | EntityAdded?.Invoke(this, eventArgs); 35 | } 36 | } 37 | public class Repository : RepositoryBase 38 | { 39 | private static List _data = new(); 40 | 41 | public override void Add(T entity) 42 | { 43 | _data.Add(entity); 44 | // don't forget to add this! 45 | OnEntityAdded(new EntityAddedEventArgs(entity)); 46 | } 47 | } 48 | 49 | public abstract class RepositoryBase2 : IWriteRepository 50 | { 51 | public event EventHandler> EntityAdded; 52 | 53 | // derived classes should call base.Add(entity) after their functionality 54 | public virtual void Add(T entity) 55 | { 56 | OnEntityAdded(new EntityAddedEventArgs(entity)); 57 | } 58 | 59 | protected virtual void OnEntityAdded(EntityAddedEventArgs eventArgs) 60 | { 61 | EntityAdded?.Invoke(this, eventArgs); 62 | } 63 | 64 | } 65 | public class Repository2 : RepositoryBase2 66 | { 67 | private static List _data = new(); 68 | 69 | public override void Add(T entity) 70 | { 71 | _data.Add(entity); 72 | // don't forget to add this! 73 | base.Add(entity); 74 | } 75 | } 76 | 77 | public abstract class RepositoryBase3 : IWriteRepository 78 | { 79 | public event EventHandler> EntityAdded; 80 | 81 | // often named AddImpl, DoAdd, DerivedAdd, etc. 82 | protected abstract void DoAdd(T entity); 83 | 84 | public void Add(T entity) 85 | { 86 | DoAdd(entity); 87 | OnEntityAdded(new EntityAddedEventArgs(entity)); 88 | } 89 | 90 | protected virtual void OnEntityAdded(EntityAddedEventArgs eventArgs) 91 | { 92 | EntityAdded?.Invoke(this, eventArgs); 93 | } 94 | } 95 | public class Repository3 : RepositoryBase3 96 | { 97 | private static List _data = new(); 98 | 99 | protected override void DoAdd(T entity) 100 | { 101 | _data.Add(entity); 102 | } 103 | } 104 | 105 | } -------------------------------------------------------------------------------- /src/M5/after/EventsDelegates/BuiltinDelegates.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | // avoid adding delegates to the global namespace 5 | namespace BuiltinDelegates 6 | { 7 | // define a delegate type which gives a name (Operation) 8 | // to a method signature: T MethodName(T op1, T op2) 9 | public delegate T Operation(T op1, T op2); 10 | 11 | public class NewMath where T : struct 12 | { 13 | // define an instance of the delegate (defaulting to null) 14 | public Operation Add; 15 | 16 | private readonly Predicate _predicate; 17 | private readonly Action _outputIgnoredItems; 18 | private List _args = new(); 19 | 20 | public NewMath(IEnumerable args, Operation addFunction, Predicate predicate, Action outputIgnoredItems = null) 21 | { 22 | Add += addFunction; 23 | _predicate = predicate; 24 | _outputIgnoredItems = outputIgnoredItems; 25 | _args.AddRange(args); 26 | } 27 | 28 | public T Sum() 29 | { 30 | T total = default(T); 31 | foreach (var arg in _args) 32 | { 33 | if (_predicate(arg)) 34 | { 35 | total = Add(total, arg); 36 | } 37 | else 38 | { 39 | _outputIgnoredItems?.Invoke(arg); 40 | } 41 | } 42 | return total; 43 | } 44 | } 45 | 46 | public static class DelegateRunner 47 | { 48 | public static bool Big(int input) 49 | { 50 | return input > 1000; 51 | } 52 | 53 | public static void Execute() 54 | { 55 | var input = new[] { 10, 1200, 20, 2000 }; 56 | // var instance = new NewMath(input, (a, b) => a + b, Big, (i) => Console.WriteLine($"Ignoring {i}.")); 57 | var instance = new NewMath(input, (a, b) => a + b, Big); 58 | 59 | Console.WriteLine($"NewMath filtered sum is {instance.Sum()}"); 60 | 61 | 62 | } 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | //Predicate predicate = Big; 78 | //Foo(Big); 79 | //Foo(predicate); 80 | 81 | public static void Foo(Predicate predicate) 82 | { 83 | // how to convert 84 | // _args.Where(_predicate); ERROR cannot convert from Predicate to Func 85 | Predicate big = x => x > 1000; 86 | Func FuncBig = new Func(big); 87 | 88 | 89 | 90 | // Predicate 91 | Predicate predicate = i => i > 10; 92 | var result = intArray.Where(predicate); // ERROR – LINQ doesn’t work with Predicate 93 | 94 | // Func Func filter = i=> I > 10; // semantically equivalent 95 | result = intArray.Where(filter); // OK 96 | 97 | // conversion – given predicate above 98 | result = intArray.Where(i => predicate(i)); 99 | result = intArray.Where(predicate); 100 | } 101 | } 102 | } -------------------------------------------------------------------------------- /src/M5/after/EventsDelegates/DataLoader.cs: -------------------------------------------------------------------------------- 1 | using Repositories; 2 | using System.Collections.Generic; 3 | 4 | namespace ClassesMethods 5 | { 6 | public class DataLoader 7 | { 8 | private readonly IWriteRepository _repo; 9 | private int counter = 0; 10 | public DataLoader(IWriteRepository repository) 11 | { 12 | _repo = repository; 13 | _repo.EntityAdded += _repo_EntityAdded; 14 | } 15 | 16 | public int Counter => counter; 17 | 18 | private void _repo_EntityAdded(object sender, EntityAddedEventArgs args) 19 | { 20 | counter++; 21 | } 22 | 23 | public void Load(IEnumerable data) 24 | { 25 | foreach (var entity in data) 26 | { 27 | _repo.Add(entity); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/M5/after/EventsDelegates/Delegates.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | // avoid adding delegates to the global namespace 5 | namespace Delegates 6 | { 7 | // define a delegate type which gives a name (Operation) 8 | // to a method signature: T MethodName(T op1, T op2) 9 | public delegate T Operation(T op1, T op2); 10 | 11 | public class NewMath where T : struct 12 | { 13 | // define an instance of the delegate (defaulting to null) 14 | public Operation Add; 15 | 16 | private T _op1; 17 | private T _op2; 18 | 19 | public NewMath(T op1, T op2, Operation addFunction) 20 | { 21 | Add += addFunction; 22 | Add += addFunction; // note you can wire up more than one function, just like events 23 | _op1 = op1; 24 | _op2 = op2; 25 | } 26 | 27 | public T Sum() 28 | { 29 | return Add(_op1, _op2); 30 | } 31 | } 32 | public static class DelegateRunner 33 | { 34 | public static int MyAdd(int op1, int op2) 35 | { 36 | return (new[] { op1, op2 }).Sum(); 37 | } 38 | 39 | public static void Execute() 40 | { 41 | var instance = new NewMath(1, 2, MyAdd); 42 | } 43 | 44 | static int sum = 0; 45 | public static void Execute2() 46 | { 47 | var instance = new NewMath(1, 2, (a,b) => { 48 | sum += a; 49 | sum += b; 50 | return sum; 51 | }); 52 | 53 | Console.WriteLine($"Adding 1 and 2 yields {instance.Sum()}"); // if 2 functions are wired up, the sum will be 6 not 3 because the methods all run 54 | 55 | var another = new NewMath(1.5m, 2.2m, (a, b) => a + b); 56 | Console.WriteLine($"Adding decimal values yields {another.Sum()}"); 57 | 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /src/M5/after/EventsDelegates/EventsDelegates.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/M5/after/EventsDelegates/EventsDelegates.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31205.134 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventsDelegates", "EventsDelegates.csproj", "{F151A9BC-AE73-4B47-9E53-52CD4862CF66}" 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 | {F151A9BC-AE73-4B47-9E53-52CD4862CF66}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {F151A9BC-AE73-4B47-9E53-52CD4862CF66}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {F151A9BC-AE73-4B47-9E53-52CD4862CF66}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {F151A9BC-AE73-4B47-9E53-52CD4862CF66}.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 = {79FBF746-E71B-4AF6-AA2B-D1728CC68B80} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /src/M5/after/EventsDelegates/Program.cs: -------------------------------------------------------------------------------- 1 | using Repositories; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace ClassesMethods 7 | { 8 | class Program 9 | { 10 | static void Main(string[] args) 11 | { 12 | Console.WriteLine("Generic Events and Delegates"); 13 | 14 | //Delegates.DelegateRunner.Execute(); 15 | BuiltinDelegates.DelegateRunner.Execute(); 16 | return; 17 | 18 | // int count = 0; 19 | // var authorRepo = new Repository(); 20 | // authorRepo.EntityAdded += Repo_EntityAdded; 21 | // authorRepo.EntityAdded += (o,e) => count++; 22 | // authorRepo.Add(new Author("Steve", "Smith")); 23 | // Console.WriteLine($"{count} authors added."); 24 | 25 | // use data loaders 26 | var authorRepo = new Repository(); 27 | var courseRepo = new Repository(); 28 | 29 | var authorLoader = new DataLoader(authorRepo); 30 | var courseLoader = new DataLoader(courseRepo); 31 | 32 | authorLoader.Load(Authors()); 33 | Console.WriteLine($"Loaded {authorLoader.Counter} authors."); 34 | courseLoader.Load(Courses()); 35 | Console.WriteLine($"Loaded {courseLoader.Counter} courses."); 36 | 37 | // print them all 38 | Console.WriteLine("Listing all authors:"); 39 | var authors = authorRepo.List(); 40 | foreach (var author in authors) 41 | { 42 | Console.WriteLine(author); 43 | } 44 | Console.WriteLine("Listing all courses:"); 45 | var courses = courseRepo.List(); 46 | foreach (var course in courses) 47 | { 48 | Console.WriteLine(course); 49 | } 50 | 51 | } 52 | private static void Repo_EntityAdded(object sender, EntityAddedEventArgs args) 53 | { 54 | Console.WriteLine($"Author added: {args.EntityAdded} (via Program.cs) by {sender}"); 55 | } 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | static void Main2(string[] args) 69 | { 70 | Console.WriteLine("Generic Events and Delegates"); 71 | 72 | LoadData(new[] { typeof(Author), typeof(Course) }); 73 | 74 | var authorRepo = new Repository(); 75 | var courseRepo = new Repository(); 76 | var dataloader = new DataLoader(authorRepo); 77 | dataloader.Load(Authors()); 78 | 79 | //repo.EntityAdded += Repo_EntityAdded; 80 | //repo.Add(author); 81 | 82 | Console.WriteLine($"{dataloader.Counter} record(s) added."); 83 | 84 | var authors = authorRepo.List(); 85 | var courses = courseRepo.List(); 86 | 87 | foreach (var author in authors) 88 | { 89 | Console.WriteLine(author); 90 | } 91 | foreach (var course in courses) 92 | { 93 | Console.WriteLine(course); 94 | } 95 | } 96 | 97 | 98 | 99 | private static void LoadData(Type[] types) 100 | { 101 | var loaderType = typeof(DataLoader<>); 102 | var repoType = typeof(Repository<>); // a container would use an interface here 103 | foreach (Type type in types) 104 | { 105 | var repoConstructed = repoType.MakeGenericType(new[] { type }); 106 | var repoInstance = Activator.CreateInstance(repoConstructed); 107 | 108 | var loaderConstructed = loaderType.MakeGenericType(new[] { type }); 109 | dynamic loaderInstance = Activator.CreateInstance(loaderConstructed, repoInstance); 110 | 111 | // could also use reflection for this 112 | if (type.Name == "Author") 113 | { 114 | loaderInstance.Load(Authors()); 115 | } 116 | else 117 | { 118 | loaderInstance.Load(Courses()); 119 | } 120 | 121 | Console.WriteLine($"Loaded {loaderInstance.Counter} {type.Name} records."); 122 | } 123 | } 124 | 125 | 126 | public static IEnumerable Authors() 127 | { 128 | yield return new Author("Steve", "Smith"); 129 | } 130 | public static IEnumerable Courses() 131 | { 132 | yield return new Course("Domain-Driven Design Fundamentals"); 133 | yield return new Course("Kanban: Getting Started"); 134 | yield return new Course("C# Design Patterns: Rules Engine Pattern"); 135 | yield return new Course("C# Design patterns: Memento"); 136 | yield return new Course("C# Design Patterns: Template Method"); 137 | yield return new Course("Design Patterns Overview"); 138 | yield return new Course("C# Design Patterns: Singleton"); 139 | yield return new Course("C# Design Patterns: Proxy"); 140 | yield return new Course("C# Design Patterns: Adapter"); 141 | yield return new Course("Refactoring for C# Developers"); 142 | yield return new Course("SOLID Principles for C# Developers"); 143 | } 144 | } 145 | 146 | public record Author(string FirstName, string LastName); 147 | public record Course(string CourseName); 148 | } 149 | -------------------------------------------------------------------------------- /src/M5/after/EventsDelegates/Repositories.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Collections.Generic; 3 | using Microsoft.Extensions.Caching; 4 | using Microsoft.Extensions.Caching.Memory; 5 | using System; 6 | 7 | namespace Repositories 8 | { 9 | public interface IWriteRepository 10 | { 11 | void Add(T entity); 12 | event EventHandler> EntityAdded; 13 | } 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | public class Repository : IReadRepository, IWriteRepository 23 | { 24 | private static List _data = new(); 25 | public IEnumerable List() 26 | { 27 | return _data.AsEnumerable(); 28 | } 29 | 30 | public void Add(T entity) 31 | { 32 | _data.Add(entity); 33 | OnEntityAdded(new EntityAddedEventArgs(entity)); 34 | } 35 | 36 | public event EventHandler> EntityAdded; 37 | protected virtual void OnEntityAdded(EntityAddedEventArgs eventArgs) 38 | { 39 | EntityAdded?.Invoke(this, eventArgs); 40 | } 41 | } 42 | 43 | 44 | 45 | 46 | // using an EventArgs type makes design more extensible 47 | public class EntityAddedEventArgs : EventArgs 48 | { 49 | public EntityAddedEventArgs(T entityAdded) 50 | { 51 | EntityAdded = entityAdded; 52 | } 53 | 54 | public T EntityAdded { get; } 55 | } 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | public interface IReadRepository 64 | { 65 | IEnumerable List(); 66 | } 67 | 68 | 69 | 70 | // an example decorator for a repository that adds simple caching 71 | // see https://ardalis.com/building-a-cachedrepository-in-aspnet-core/ 72 | public class CachedRepository : IReadRepository 73 | { 74 | private readonly IReadRepository _sourceRepo; 75 | private readonly IMemoryCache _cache; 76 | public CachedRepository(IReadRepository sourceRepo, 77 | MemoryCache cache) 78 | { 79 | _sourceRepo = sourceRepo; 80 | _cache = cache; 81 | } 82 | 83 | public IEnumerable List() 84 | { 85 | string key = nameof(T); 86 | 87 | var result = _cache.GetOrCreate(key, entry => 88 | { 89 | //entry. 90 | return _sourceRepo.List(); 91 | }); 92 | 93 | return result; 94 | } 95 | } 96 | } --------------------------------------------------------------------------------