├── .gitignore ├── README.md ├── ReflectionSample.sln └── ReflectionSample ├── DemoClasses.cs ├── IoCContainer.cs ├── IoCContainerClasses.cs ├── NetworkMonitorClasses.cs ├── Program.cs ├── ReflectionSample.csproj ├── ResultOfT.cs └── appsettings.json /.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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Reflection in C# 2 | Fully functioning sample for my "Using Reflection in a C# Application: Best Practices" course at Pluralsight. 3 | -------------------------------------------------------------------------------- /ReflectionSample.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30717.126 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ReflectionSample", "ReflectionSample\ReflectionSample.csproj", "{20A24446-BA66-46FE-A31F-2F8C202F881A}" 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 | {20A24446-BA66-46FE-A31F-2F8C202F881A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {20A24446-BA66-46FE-A31F-2F8C202F881A}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {20A24446-BA66-46FE-A31F-2F8C202F881A}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {20A24446-BA66-46FE-A31F-2F8C202F881A}.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 = {DE99E2BE-F612-4C0C-B0B2-94F4AC50E259} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /ReflectionSample/DemoClasses.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ReflectionSample 8 | { 9 | public interface ITalk 10 | { 11 | void Talk(string sentence); 12 | } 13 | 14 | public class EmployeeMarkerAttribute : Attribute 15 | { 16 | } 17 | 18 | [EmployeeMarker] 19 | public class Employee : Person 20 | { 21 | public string Company { get; set; } 22 | } 23 | 24 | public class Alien : ITalk 25 | { 26 | public void Talk(string sentence) 27 | { 28 | // talk... 29 | Console.WriteLine($"Alien talking...: {sentence}"); 30 | } 31 | } 32 | 33 | public class Person : ITalk 34 | { 35 | public string Name { get; set; } 36 | public int age; 37 | private string _aPrivateField = "initial private field value"; 38 | 39 | public Person() 40 | { 41 | Console.WriteLine("A person is being created."); 42 | } 43 | 44 | public Person(string name) 45 | { 46 | Console.WriteLine($"A person with name {name} is being created."); 47 | Name = name; 48 | } 49 | 50 | private Person(string name, int age) 51 | { 52 | Console.WriteLine($"A person with name {name} and age {age} " + 53 | $"is being created using a private constructor."); 54 | Name = name; 55 | this.age = age; 56 | } 57 | 58 | public void Talk(string sentence) 59 | { 60 | // talk... 61 | Console.WriteLine($"Talking...: {sentence}"); 62 | } 63 | 64 | protected void Yell(string sentence) 65 | { 66 | // yell... 67 | Console.WriteLine($"YELLING! {sentence}"); 68 | } 69 | 70 | public override string ToString() 71 | { 72 | return $"{Name} {age} {_aPrivateField}"; 73 | } 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /ReflectionSample/IoCContainer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace ReflectionSample 9 | { 10 | public class IoCContainer 11 | { 12 | Dictionary _map = new Dictionary(); 13 | MethodInfo _resolveMethod; 14 | 15 | public void Register() 16 | { 17 | // register in the mapping dictionary 18 | if (!_map.ContainsKey(typeof(TContract))) 19 | { 20 | _map.Add(typeof(TContract), typeof(TImplementation)); 21 | } 22 | } 23 | 24 | public void Register(Type contract, Type implementation) 25 | { 26 | // register in the mapping dictionary 27 | if (!_map.ContainsKey(contract)) 28 | { 29 | _map.Add(contract, implementation); 30 | } 31 | } 32 | 33 | public TContract Resolve() 34 | { 35 | // check whether we're trying to resolve a generic type 36 | if (typeof(TContract).IsGenericType && 37 | _map.ContainsKey(typeof(TContract).GetGenericTypeDefinition())) 38 | { 39 | var openImplementation = _map[typeof(TContract).GetGenericTypeDefinition()]; 40 | var closedImplementation = openImplementation 41 | .MakeGenericType(typeof(TContract).GenericTypeArguments); 42 | return Create(closedImplementation); 43 | } 44 | 45 | if (!_map.ContainsKey(typeof(TContract))) 46 | { 47 | throw new ArgumentException($"No registration found for {typeof(TContract)}"); 48 | } 49 | 50 | // create an instance and return it 51 | return Create(_map[typeof(TContract)]); 52 | } 53 | 54 | private TContract Create(Type implementationType) 55 | { 56 | // get the resolve method. 57 | if (_resolveMethod == null) 58 | { 59 | _resolveMethod = typeof(IoCContainer).GetMethod("Resolve"); 60 | } 61 | 62 | var constructorParameters = implementationType.GetConstructors() 63 | .OrderByDescending(c => c.GetParameters().Length) 64 | .First() 65 | .GetParameters() 66 | .Select(p => 67 | { 68 | // make the resolve method generic and invoke it 69 | var genericResolveMethod = _resolveMethod 70 | .MakeGenericMethod(p.ParameterType); 71 | return genericResolveMethod.Invoke(this, null); 72 | }) 73 | .ToArray(); 74 | 75 | return (TContract)Activator.CreateInstance( 76 | implementationType, constructorParameters); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /ReflectionSample/IoCContainerClasses.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ReflectionSample 8 | { 9 | public class CoffeeService : ICoffeeService 10 | { 11 | public CoffeeService(IWaterService waterService) 12 | { 13 | } 14 | 15 | public CoffeeService(IWaterService waterService, 16 | IBeanService beanService) 17 | { 18 | } 19 | } 20 | 21 | public interface ICoffeeService 22 | { } 23 | 24 | public class TapWaterService : IWaterService 25 | { } 26 | 27 | public interface IWaterService 28 | { } 29 | 30 | public class ArabicaBeanService : IBeanService 31 | { } 32 | 33 | public interface IBeanService 34 | { } 35 | 36 | /// 37 | /// Variety of the Arabica coffee bean 38 | /// 39 | public class Catimor 40 | { } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /ReflectionSample/NetworkMonitorClasses.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ReflectionSample 8 | { 9 | public class MailService 10 | { 11 | public void SendMail(string address, string subject) 12 | { 13 | Console.WriteLine($"Sending a warning mail to {address} with subject {subject}."); 14 | } 15 | } 16 | 17 | public class SoundHornService 18 | { 19 | public void SoundHorn(string volume) 20 | { 21 | Console.WriteLine($"Making noise with the volume turned up to {volume}."); 22 | } 23 | } 24 | 25 | public class NetworkMonitorSettings 26 | { 27 | public string WarningService { get; set; } 28 | public string MethodToExecute { get; set; } 29 | public Dictionary PropertyBag { get; set; } = 30 | new Dictionary(StringComparer.OrdinalIgnoreCase); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /ReflectionSample/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using ReflectionMagic; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Reflection; 6 | 7 | namespace ReflectionSample 8 | { 9 | class Program 10 | { 11 | private static string _typeFromConfiguration = "ReflectionSample.Person"; 12 | private static NetworkMonitorSettings _networkMonitorSettings = new NetworkMonitorSettings(); 13 | private static Type _warningServiceType; 14 | private static MethodInfo _warningServiceMethod; 15 | private static object _warningService; 16 | private static List _warningServiceParameterValues; 17 | 18 | static void Main(string[] args) 19 | { 20 | var person = new Person("Kevin"); 21 | 22 | var privateField = person.GetType().GetField("_aPrivateField", 23 | BindingFlags.Instance | BindingFlags.NonPublic); 24 | privateField.SetValue(person, "New private field value"); 25 | 26 | person.AsDynamic()._aPrivateField = "Updated value via ReflectionMagic"; 27 | 28 | //person.AsDynamic().MyMethod()... 29 | //person.AsDynamic().MyProperty = ... 30 | 31 | Console.ReadLine(); 32 | } 33 | 34 | public void Generics() 35 | { 36 | var myList = new List(); 37 | Console.WriteLine(myList.GetType().Name); 38 | 39 | Console.WriteLine(myList.GetType()); 40 | 41 | var myDictionary = new Dictionary(); 42 | Console.WriteLine(myDictionary.GetType()); 43 | 44 | var dictionaryType = myDictionary.GetType(); 45 | foreach (var genericTypeArgument in dictionaryType.GenericTypeArguments) 46 | { 47 | Console.WriteLine(genericTypeArgument); 48 | } 49 | foreach (var genericArgument in dictionaryType.GetGenericArguments()) 50 | { 51 | Console.WriteLine(genericArgument); 52 | } 53 | 54 | var openDictionaryType = typeof(Dictionary<,>); 55 | foreach (var genericTypeArgument in openDictionaryType.GenericTypeArguments) 56 | { 57 | Console.WriteLine(genericTypeArgument); 58 | } 59 | foreach (var genericArgument in openDictionaryType.GetGenericArguments()) 60 | { 61 | Console.WriteLine(genericArgument); 62 | } 63 | 64 | var createdInstance = Activator.CreateInstance(typeof(List)); 65 | Console.WriteLine(createdInstance.GetType()); 66 | 67 | //var createdResult = Activator.CreateInstance(typeof(Result<>)); 68 | 69 | //var openResultType = typeof(Result<>); 70 | //var closedResultType = openResultType.MakeGenericType(typeof(Person)); 71 | //var createdResult = Activator.CreateInstance(closedResultType); 72 | 73 | var openResultType = Type.GetType("ReflectionSample.Result`1"); 74 | var closedResultType = openResultType.MakeGenericType( 75 | Type.GetType("ReflectionSample.Person")); 76 | var createdResult = Activator.CreateInstance(closedResultType); 77 | 78 | Console.WriteLine(createdResult.GetType()); 79 | 80 | var methodInfo = closedResultType.GetMethod("AlterAndReturnValue"); 81 | Console.WriteLine(methodInfo); 82 | 83 | var genericMethodInfo = methodInfo.MakeGenericMethod(typeof(Employee)); 84 | genericMethodInfo.Invoke(createdResult, new object[] { new Employee() }); 85 | 86 | var iocContainer = new IoCContainer(); 87 | iocContainer.Register(); 88 | var waterService = iocContainer.Resolve(); 89 | 90 | //iocContainer.Register, ArabicaBeanService>(); 91 | //iocContainer.Register, ArabicaBeanService<>>(); 92 | //iocContainer.Register < typeof(IBeanService<>), typeof(ArabicaBeanService<>) > (); 93 | 94 | iocContainer.Register(typeof(IBeanService<>), typeof(ArabicaBeanService<>)); 95 | 96 | iocContainer.Register(); 97 | var coffeeService = iocContainer.Resolve(); 98 | } 99 | 100 | public void NetworkMonitorExample() 101 | { 102 | BootStrapFromConfiguration(); 103 | 104 | Console.WriteLine("Monitoring network... something went wrong."); 105 | 106 | Warn(); 107 | } 108 | 109 | private static void Warn() 110 | { 111 | // first, create an instance of the service if it wasn't cached yet 112 | if (_warningService == null) 113 | { 114 | _warningService = Activator.CreateInstance(_warningServiceType); 115 | } 116 | 117 | // then, call the method on it, passing through the property bag 118 | // create a list of parameters 119 | var parameters = new List(); 120 | foreach (var propertyBagItem in _networkMonitorSettings.PropertyBag) 121 | { 122 | parameters.Add(propertyBagItem.Value); 123 | } 124 | 125 | _warningServiceMethod.Invoke(_warningService, parameters.ToArray()); 126 | } 127 | 128 | private static void BootStrapFromConfiguration() 129 | { 130 | var appSettingsConfig = new ConfigurationBuilder() 131 | .AddJsonFile("appsettings.json", true, true) 132 | .Build(); 133 | 134 | appSettingsConfig.Bind("NetworkMonitorSettings", _networkMonitorSettings); 135 | 136 | // inspect the assembly to check whether the correct types are contained within 137 | _warningServiceType = Assembly.GetExecutingAssembly() 138 | .GetType(_networkMonitorSettings.WarningService); 139 | if (_warningServiceType == null) 140 | { 141 | throw new Exception("Configuration is invalid - warning service not found"); 142 | } 143 | 144 | // inspect the service for the required method 145 | _warningServiceMethod = _warningServiceType 146 | .GetMethod(_networkMonitorSettings.MethodToExecute); 147 | if (_warningServiceMethod == null) 148 | { 149 | throw new Exception("Configuration is invalid - method to execute " + 150 | "on warning service not found"); 151 | } 152 | 153 | // check if the parameters match 154 | foreach (var parameterInfo in _warningServiceMethod.GetParameters()) 155 | { 156 | if (!_networkMonitorSettings.PropertyBag.TryGetValue( 157 | parameterInfo.Name, out object parameterValue)) 158 | { 159 | // parameter name cannot be found 160 | throw new Exception($"Configuration is invalid - parameter " + 161 | $"{parameterInfo.Name} not found."); 162 | }; 163 | 164 | _warningServiceParameterValues = new List(); 165 | try 166 | { 167 | var typedValue = Convert.ChangeType( 168 | parameterValue, parameterInfo.ParameterType); 169 | _warningServiceParameterValues.Add(typedValue); 170 | } 171 | catch 172 | { 173 | throw new Exception($"Configuration is invalid - parameter {parameterInfo.Name} " + 174 | $"cannot be converted to expected type {parameterInfo.ParameterType}."); 175 | } 176 | } 177 | } 178 | 179 | public void InstantiatingAndManipulatingObjects() 180 | { 181 | var personType = typeof(Person); 182 | var personConstructors = personType.GetConstructors( 183 | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); 184 | 185 | foreach (var personConstructor in personConstructors) 186 | { 187 | Console.WriteLine(personConstructor); 188 | } 189 | 190 | var privatePersonConstructor = personType.GetConstructor( 191 | BindingFlags.Instance | BindingFlags.NonPublic, 192 | null, 193 | new Type[] { typeof(string), typeof(int) }, 194 | null); 195 | 196 | Console.WriteLine(privatePersonConstructor); 197 | 198 | var person1 = personConstructors[0].Invoke(null); 199 | 200 | var person2 = personConstructors[1].Invoke(new object[] { "Kevin" }); 201 | 202 | var person3 = personConstructors[2].Invoke(new object[] { "Kevin", 39 }); 203 | 204 | var person4 = Activator.CreateInstance( 205 | "ReflectionSample", "ReflectionSample.Person").Unwrap(); 206 | 207 | var person5 = Activator.CreateInstance("ReflectionSample", 208 | "ReflectionSample.Person", 209 | true, 210 | BindingFlags.Instance | BindingFlags.Public, 211 | null, 212 | new object[] { "Kevin" }, 213 | null, 214 | null); 215 | 216 | var personTypeFromString = Type.GetType("ReflectionSample.Person"); 217 | var person6 = Activator.CreateInstance(personTypeFromString, 218 | new object[] { "Kevin" }); 219 | 220 | var person7 = Activator.CreateInstance("ReflectionSample", 221 | "ReflectionSample.Person", 222 | true, 223 | BindingFlags.Instance | BindingFlags.NonPublic, 224 | null, 225 | new object[] { "Kevin", 39 }, 226 | null, 227 | null); 228 | 229 | var assembly = Assembly.GetExecutingAssembly(); 230 | var person8 = assembly.CreateInstance("ReflectionSample.Person"); 231 | 232 | // create a new instance of a configured type 233 | var actualTypeFromConfiguration = Type.GetType(_typeFromConfiguration); 234 | var iTalkInstance = Activator.CreateInstance(actualTypeFromConfiguration) as ITalk; 235 | iTalkInstance.Talk("Hello world!"); 236 | 237 | dynamic dynamicITalkInstance = Activator.CreateInstance(actualTypeFromConfiguration); 238 | dynamicITalkInstance.Talk("Hello world!"); 239 | 240 | var personForManipulation = Activator.CreateInstance("ReflectionSample", 241 | "ReflectionSample.Person", 242 | true, 243 | BindingFlags.Instance | BindingFlags.NonPublic, 244 | null, 245 | new object[] { "Kevin", 39 }, 246 | null, 247 | null).Unwrap(); 248 | 249 | var nameProperty = personForManipulation.GetType().GetProperty("Name"); 250 | nameProperty.SetValue(personForManipulation, "Sven"); 251 | 252 | var ageField = personForManipulation.GetType().GetField("age"); 253 | ageField.SetValue(personForManipulation, 34); 254 | 255 | var privateField = personForManipulation.GetType().GetField("_aPrivateField", 256 | BindingFlags.Instance | BindingFlags.NonPublic); 257 | privateField.SetValue(personForManipulation, "updated private field value"); 258 | 259 | personForManipulation.GetType().InvokeMember("Name", 260 | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, 261 | null, personForManipulation, new[] { "Emma" }); 262 | 263 | personForManipulation.GetType().InvokeMember("_aPrivateField", 264 | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField, 265 | null, personForManipulation, new[] { "second update for private field value" }); 266 | 267 | Console.WriteLine(personForManipulation); 268 | 269 | var talkMethod = personForManipulation.GetType().GetMethod("Talk"); 270 | talkMethod.Invoke(personForManipulation, new[] { "something to say" }); 271 | 272 | personForManipulation.GetType().InvokeMember("Yell", 273 | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, 274 | null, personForManipulation, new[] { "something to yell" }); 275 | } 276 | 277 | public void InspectingMetadata() 278 | { 279 | string name = "Kevin"; 280 | //var stringType = name.GetType(); 281 | var stringType = typeof(string); 282 | Console.WriteLine(stringType); 283 | 284 | var currentAssembly = Assembly.GetExecutingAssembly(); 285 | var typesFromCurrentAssembly = currentAssembly.GetTypes(); 286 | foreach (var type in typesFromCurrentAssembly) 287 | { 288 | Console.WriteLine(type.Name); 289 | } 290 | 291 | var oneTypeFromCurrentAssembly = currentAssembly.GetType("ReflectionSample.Person"); 292 | Console.WriteLine(oneTypeFromCurrentAssembly.Name); 293 | 294 | var externalAssembly = Assembly.Load("System.Text.Json"); 295 | var typesFromExternalAssembly = externalAssembly.GetTypes(); 296 | var oneTypeFromExternalAssembly = externalAssembly.GetType("System.Text.Json.JsonProperty"); 297 | 298 | var modulesFromExternalAssembly = externalAssembly.GetModules(); 299 | var oneModuleFromExternalAssembly = externalAssembly.GetModule("System.Text.Json.dll"); 300 | 301 | var typesFromModuleFromExternalAssembly = oneModuleFromExternalAssembly.GetTypes(); 302 | var oneTypeFromModuleFromExternalAssembly = 303 | oneModuleFromExternalAssembly.GetType("System.Text.Json.JsonProperty"); 304 | 305 | foreach (var constructor in oneTypeFromCurrentAssembly.GetConstructors()) 306 | { 307 | Console.WriteLine(constructor); 308 | } 309 | 310 | //foreach (var method in oneTypeFromCurrentAssembly.GetMethods()) 311 | //{ 312 | // Console.WriteLine(method); 313 | //} 314 | 315 | foreach (var method in oneTypeFromCurrentAssembly.GetMethods( 316 | BindingFlags.Public | BindingFlags.NonPublic)) 317 | { 318 | Console.WriteLine($"{method}, public: {method.IsPublic}"); 319 | } 320 | 321 | foreach (var field in oneTypeFromCurrentAssembly.GetFields( 322 | BindingFlags.Instance | BindingFlags.NonPublic)) 323 | { 324 | Console.WriteLine(field); 325 | } 326 | } 327 | } 328 | } 329 | -------------------------------------------------------------------------------- /ReflectionSample/ReflectionSample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 9.0 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Always 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /ReflectionSample/ResultOfT.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ReflectionSample 8 | { 9 | public class Result 10 | { 11 | public T Value { get; set; } 12 | public string Remarks { get; set; } 13 | 14 | public T AlterAndReturnValue(S input) 15 | { 16 | // dummy code... 17 | Console.WriteLine($"Altering value using {input.GetType()}"); 18 | return Value; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ReflectionSample/appsettings.json: -------------------------------------------------------------------------------- 1 | //{ 2 | // "NetworkMonitorSettings": { 3 | // "WarningService": "ReflectionSample.MailService", 4 | // "MethodToExecute": "SendMail", 5 | // "PropertyBag": { 6 | // "Address": "kevin.dockx@gmail.com", 7 | // "Subject": "Warning" 8 | // } 9 | // } 10 | //} 11 | 12 | { 13 | "NetworkMonitorSettings": { 14 | "WarningService": "ReflectionSample.SoundHornService", 15 | "MethodToExecute": "SoundHorn", 16 | "PropertyBag": { 17 | "Volume": "11" 18 | } 19 | } 20 | } --------------------------------------------------------------------------------