Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.15.8" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\DynamicTypeInCSharp\DynamicTypeInCSharp.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -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)!;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
using BenchmarkDotNet.Running;

BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);
62 changes: 62 additions & 0 deletions csharp-advanced-topics/DynamicTypeInCSharp/DynamicTypeInCSharp.sln
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using DynamicTypeInCSharp.Models;

namespace DynamicTypeInCSharp.Factories;

public class EmployeeFactory
{
private readonly List<Employee> _employees = [];

public void Add(Employee employee)
{
_employees.Add(employee);
}

public object GetFirstEmployee()
{
return _employees.First();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using DynamicTypeInCSharp.Models;

namespace DynamicTypeInCSharp.Factories;

public class LoggerFactory
{
public static Logger GetLogger()
{
return new Logger();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace DynamicTypeInCSharp.Models;

public record Book(string Isbn);
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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}");
}
}
Original file line number Diff line number Diff line change
@@ -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();
}
Original file line number Diff line number Diff line change
@@ -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<RuntimeBinderException>(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<RuntimeBinderException>(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<RuntimeBinderException>(() => 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<DynamicAttribute>());
}

private static void TakesDynamic(dynamic value) => _ = value;
}
Loading
Loading