C# - TPL2141 logo C# - TPL2141

Variables with the type of dynamic will bypass static type checking, errors will only be caught on runtime (Docs, 2015).

dynamic number = 123;
number = number + 456;
Console.WriteLine($"Value: {number}\tType: {number.GetType()}");

Output:

Value: 579  Type: System.Int32

We are allowed to assign a string to the same variable (which is initially an int).

number = "a string";
Console.WriteLine($"Value: {number}\tType: {number.GetType()}");

Output:

Value: a string Type: System.String

Because the variable is now a string, subtracting an int will result in a runtime error

number = number - 1;
// ERROR: Operator '-' cannot be applied to operands of type 'string' and 'int'

Live-code example

References

  1. Docs, M. (Ed.). (2015, July 20). dynamic (C# Reference). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/dynamic