From b2d475c6980c5278ff6d32b3671c432f8e8d2174 Mon Sep 17 00:00:00 2001 From: Vladimir Pecanac Date: Fri, 13 Nov 2026 14:25:58 +0100 Subject: [PATCH] Add DynamicTypeInCSharp sample (net11.0, tests, benchmark) Migrates the Dynamic Type in C# sample into CodeMazeGuides: console project with every article example, six xUnit tests, and a BenchmarkDotNet project comparing static, dynamic and reflection calls. --- .../Benchmarks/Benchmarks.csproj | 18 ++++ .../Benchmarks/MethodCallBenchmarks.cs | 31 ++++++ .../DynamicTypeInCSharp/Benchmarks/Program.cs | 3 + .../DynamicTypeInCSharp.sln | 62 ++++++++++++ .../DynamicTypeInCSharp.csproj | 10 ++ .../DynamicTypeInCSharp/Examples.cs | 94 +++++++++++++++++++ .../Factories/EmployeeFactory.cs | 18 ++++ .../Factories/LoggerFactory.cs | 11 +++ .../DynamicTypeInCSharp/Models/Book.cs | 3 + .../DynamicTypeInCSharp/Models/Employee.cs | 20 ++++ .../DynamicTypeInCSharp/Models/Logger.cs | 19 ++++ .../DynamicTypeInCSharp/Program.cs | 24 +++++ .../Tests/DynamicTypeTests.cs | 64 +++++++++++++ .../DynamicTypeInCSharp/Tests/Tests.csproj | 32 +++++++ 14 files changed, 409 insertions(+) create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/Benchmarks.csproj create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/MethodCallBenchmarks.cs create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/Program.cs create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp.sln create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/DynamicTypeInCSharp.csproj create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Examples.cs create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Factories/EmployeeFactory.cs create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Factories/LoggerFactory.cs create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Book.cs create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Employee.cs create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Logger.cs create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Program.cs create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/Tests/DynamicTypeTests.cs create mode 100644 csharp-advanced-topics/DynamicTypeInCSharp/Tests/Tests.csproj diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/Benchmarks.csproj b/csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/Benchmarks.csproj new file mode 100644 index 0000000000..76db81baba --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/Benchmarks.csproj @@ -0,0 +1,18 @@ + + + + Exe + net11.0 + enable + enable + + + + + + + + + + + diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/MethodCallBenchmarks.cs b/csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/MethodCallBenchmarks.cs new file mode 100644 index 0000000000..97d44d7920 --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/MethodCallBenchmarks.cs @@ -0,0 +1,31 @@ +using System.Reflection; +using BenchmarkDotNet.Attributes; +using DynamicTypeInCSharp.Models; + +namespace Benchmarks; + +[InProcess] +[MemoryDiagnoser] +public class MethodCallBenchmarks +{ + private readonly Employee _employee = new() { Id = "1", Name = "Johnny Depp" }; + private readonly object _employeeObject; + private readonly dynamic _employeeDynamic; + + public MethodCallBenchmarks() + { + _employeeObject = _employee; + _employeeDynamic = _employee; + } + + [Benchmark] + public WorkStatus StaticCall() => _employee.GetWorkStatus(); + + [Benchmark] + public WorkStatus DynamicCall() => _employeeDynamic.GetWorkStatus(); + + [Benchmark] + public WorkStatus ReflectionCall() => + (WorkStatus)_employeeObject.GetType().InvokeMember("GetWorkStatus", + BindingFlags.InvokeMethod, null, _employeeObject, null)!; +} diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/Program.cs b/csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/Program.cs new file mode 100644 index 0000000000..c9a046727c --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/Benchmarks/Program.cs @@ -0,0 +1,3 @@ +using BenchmarkDotNet.Running; + +BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp.sln b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp.sln new file mode 100644 index 0000000000..219338759e --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp.sln @@ -0,0 +1,62 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DynamicTypeInCSharp", "DynamicTypeInCSharp\DynamicTypeInCSharp.csproj", "{CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{0294EFCB-78F1-45E1-A72A-05DDA2D954EB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Benchmarks", "Benchmarks\Benchmarks.csproj", "{60D894B2-411C-4747-9D8C-D98985DBCAAD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Debug|x64.ActiveCfg = Debug|Any CPU + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Debug|x64.Build.0 = Debug|Any CPU + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Debug|x86.ActiveCfg = Debug|Any CPU + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Debug|x86.Build.0 = Debug|Any CPU + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Release|Any CPU.Build.0 = Release|Any CPU + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Release|x64.ActiveCfg = Release|Any CPU + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Release|x64.Build.0 = Release|Any CPU + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Release|x86.ActiveCfg = Release|Any CPU + {CFED5BB6-F217-4ADA-AC82-7F1521DBE47A}.Release|x86.Build.0 = Release|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Debug|x64.ActiveCfg = Debug|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Debug|x64.Build.0 = Debug|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Debug|x86.ActiveCfg = Debug|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Debug|x86.Build.0 = Debug|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Release|Any CPU.Build.0 = Release|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Release|x64.ActiveCfg = Release|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Release|x64.Build.0 = Release|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Release|x86.ActiveCfg = Release|Any CPU + {0294EFCB-78F1-45E1-A72A-05DDA2D954EB}.Release|x86.Build.0 = Release|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Debug|x64.ActiveCfg = Debug|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Debug|x64.Build.0 = Debug|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Debug|x86.ActiveCfg = Debug|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Debug|x86.Build.0 = Debug|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Release|Any CPU.Build.0 = Release|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Release|x64.ActiveCfg = Release|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Release|x64.Build.0 = Release|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Release|x86.ActiveCfg = Release|Any CPU + {60D894B2-411C-4747-9D8C-D98985DBCAAD}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/DynamicTypeInCSharp.csproj b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/DynamicTypeInCSharp.csproj new file mode 100644 index 0000000000..5bf6c9b8cf --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/DynamicTypeInCSharp.csproj @@ -0,0 +1,10 @@ + + + + Exe + net11.0 + enable + enable + + + diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Examples.cs b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Examples.cs new file mode 100644 index 0000000000..4ad6e295bc --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Examples.cs @@ -0,0 +1,94 @@ +using System.Collections; +using System.Reflection; +using DynamicTypeInCSharp.Factories; +using DynamicTypeInCSharp.Models; + +namespace DynamicTypeInCSharp; + +public static class Examples +{ + public static void ExampleDeclaration() + { + var isbn = "978-1617294532"; + + dynamic intNumber = 12; + dynamic book = new Book(isbn); + + Console.WriteLine(intNumber.GetType()); + Console.WriteLine(book.Isbn); + } + + public static void ExampleDynamicWithException() + { + dynamic testVariable = 5; + Console.WriteLine(testVariable.GetType()); + + testVariable = "Hello World"; + Console.WriteLine(testVariable.GetType()); + + Console.WriteLine(testVariable++); + } + + public static void ExampleMissingMethodDefinitionException() + { + dynamic logger = LoggerFactory.GetLogger(); + logger.LogInfo("Hi"); + logger.LogWarning("You are about to enter a time warp"); + logger.LogError("System is malfunctioning"); + logger.LogTrace("Communication lost"); + } + + public static WorkStatus ExampleReflection() + { + EmployeeFactory employeeFactory = GetEmployeeFactory(); + object firstEmployee = employeeFactory.GetFirstEmployee(); + Type firstEmployeeType = firstEmployee.GetType(); + object? workStatusObject = firstEmployeeType.InvokeMember("GetWorkStatus", + BindingFlags.InvokeMethod, null, firstEmployee, null); + var workStatus = (WorkStatus)workStatusObject!; + + Console.WriteLine(workStatus); + + return workStatus; + } + + public static WorkStatus ExampleDynamic() + { + EmployeeFactory employeeFactory = GetEmployeeFactory(); + dynamic firstEmployee = employeeFactory.GetFirstEmployee(); + WorkStatus workStatus = firstEmployee.GetWorkStatus(); + + Console.WriteLine(workStatus); + + return workStatus; + } + + public static void ExampleVarObjectDynamic() + { + var imNumber = 10; //implicitly typed variable + int exNumber = 10; //explicitly typed variable + + object testObj = 10; + testObj = (int)testObj + 10; + + dynamic testDynamic = 10; + testDynamic = testDynamic + 25; + + Console.WriteLine($"{imNumber} {exNumber} {testObj} {testDynamic}"); + } + + public static void ExamplePrintCount(ICollection collection) + { + dynamic dynamicCollection = collection; + Console.WriteLine("Static typing: {0}", collection.Count); + Console.WriteLine("Dynamic typing: {0}", dynamicCollection.Count); + } + + private static EmployeeFactory GetEmployeeFactory() + { + var employeeFactory = new EmployeeFactory(); + employeeFactory.Add(new Employee { Id = "1", Name = "Johnny Depp" }); + + return employeeFactory; + } +} diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Factories/EmployeeFactory.cs b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Factories/EmployeeFactory.cs new file mode 100644 index 0000000000..84e24284b1 --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Factories/EmployeeFactory.cs @@ -0,0 +1,18 @@ +using DynamicTypeInCSharp.Models; + +namespace DynamicTypeInCSharp.Factories; + +public class EmployeeFactory +{ + private readonly List _employees = []; + + public void Add(Employee employee) + { + _employees.Add(employee); + } + + public object GetFirstEmployee() + { + return _employees.First(); + } +} diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Factories/LoggerFactory.cs b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Factories/LoggerFactory.cs new file mode 100644 index 0000000000..ac63587b6b --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Factories/LoggerFactory.cs @@ -0,0 +1,11 @@ +using DynamicTypeInCSharp.Models; + +namespace DynamicTypeInCSharp.Factories; + +public class LoggerFactory +{ + public static Logger GetLogger() + { + return new Logger(); + } +} diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Book.cs b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Book.cs new file mode 100644 index 0000000000..bdaf23e400 --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Book.cs @@ -0,0 +1,3 @@ +namespace DynamicTypeInCSharp.Models; + +public record Book(string Isbn); diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Employee.cs b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Employee.cs new file mode 100644 index 0000000000..f88e518c20 --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Employee.cs @@ -0,0 +1,20 @@ +namespace DynamicTypeInCSharp.Models; + +public class Employee +{ + public string Id { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + public WorkStatus WorkStatus { get; set; } = WorkStatus.NotWorking; + + public WorkStatus GetWorkStatus() + { + return WorkStatus; + } +} + +public enum WorkStatus +{ + OnABreak, + Working, + NotWorking +} diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Logger.cs b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Logger.cs new file mode 100644 index 0000000000..b3d5a35c64 --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Models/Logger.cs @@ -0,0 +1,19 @@ +namespace DynamicTypeInCSharp.Models; + +public class Logger +{ + public void LogInfo(string message) + { + Console.WriteLine($"INFO: {message}"); + } + + public void LogWarning(string message) + { + Console.WriteLine($"WARNING: {message}"); + } + + public void LogError(string message) + { + Console.WriteLine($"ERROR: {message}"); + } +} diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Program.cs b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Program.cs new file mode 100644 index 0000000000..20b8790625 --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp/Program.cs @@ -0,0 +1,24 @@ +using DynamicTypeInCSharp; +using Microsoft.CSharp.RuntimeBinder; + +Run(Examples.ExampleDeclaration); +Run(Examples.ExampleDynamicWithException); +Run(Examples.ExampleMissingMethodDefinitionException); +Run(() => Examples.ExampleReflection()); +Run(() => Examples.ExampleDynamic()); +Run(Examples.ExampleVarObjectDynamic); +Run(() => Examples.ExamplePrintCount(new int[20])); + +static void Run(Action example) +{ + try + { + example(); + } + catch (RuntimeBinderException ex) + { + Console.WriteLine($"{ex.GetType().FullName}: {ex.Message}"); + } + + Console.WriteLine(); +} diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/Tests/DynamicTypeTests.cs b/csharp-advanced-topics/DynamicTypeInCSharp/Tests/DynamicTypeTests.cs new file mode 100644 index 0000000000..90cdf29562 --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/Tests/DynamicTypeTests.cs @@ -0,0 +1,64 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using DynamicTypeInCSharp; +using DynamicTypeInCSharp.Models; +using Microsoft.CSharp.RuntimeBinder; + +namespace Tests; + +public class DynamicTypeTests +{ + [Fact] + public void GivenDynamicVariable_WhenNewValueIsAssigned_ThenRuntimeTypeFollowsTheValue() + { + dynamic testVariable = 5; + Assert.Equal(typeof(int), testVariable.GetType()); + + testVariable = "Hello World"; + Assert.Equal(typeof(string), testVariable.GetType()); + } + + [Fact] + public void GivenStringInDynamicVariable_WhenIncremented_ThenRuntimeBinderExceptionIsThrown() + { + var ex = Assert.Throws(Examples.ExampleDynamicWithException); + + Assert.Equal("Operator '++' cannot be applied to operand of type 'string'", ex.Message); + } + + [Fact] + public void GivenDynamicLogger_WhenMissingMethodIsCalled_ThenRuntimeBinderExceptionIsThrown() + { + var ex = Assert.Throws(Examples.ExampleMissingMethodDefinitionException); + + Assert.Contains("does not contain a definition for 'LogTrace'", ex.Message); + } + + [Fact] + public void GivenEmployee_WhenWorkStatusIsReadByReflectionAndByDynamic_ThenBothReturnTheSameValue() + { + Assert.Equal(WorkStatus.NotWorking, Examples.ExampleReflection()); + Assert.Equal(WorkStatus.NotWorking, Examples.ExampleDynamic()); + } + + [Fact] + public void GivenArrayAsICollection_WhenCountIsReadDynamically_ThenRuntimeBinderExceptionIsThrown() + { + var ex = Assert.Throws(() => Examples.ExamplePrintCount(new int[20])); + + Assert.Equal("'System.Array' does not contain a definition for 'Count'", ex.Message); + } + + [Fact] + public void GivenDynamicParameter_WhenInspected_ThenItIsObjectWithDynamicAttribute() + { + var parameter = typeof(DynamicTypeTests) + .GetMethod(nameof(TakesDynamic), BindingFlags.NonPublic | BindingFlags.Static)! + .GetParameters()[0]; + + Assert.Equal(typeof(object), parameter.ParameterType); + Assert.NotNull(parameter.GetCustomAttribute()); + } + + private static void TakesDynamic(dynamic value) => _ = value; +} diff --git a/csharp-advanced-topics/DynamicTypeInCSharp/Tests/Tests.csproj b/csharp-advanced-topics/DynamicTypeInCSharp/Tests/Tests.csproj new file mode 100644 index 0000000000..07c23f5176 --- /dev/null +++ b/csharp-advanced-topics/DynamicTypeInCSharp/Tests/Tests.csproj @@ -0,0 +1,32 @@ + + + + net11.0 + enable + enable + false + true + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + +