Dynamic Type in C#

1 - What is the dynamic type

As we know from the anonymous types post, C# or .NET implements a type called dynamic which, as its name suggests, allows us to assign a value dynamically. 

When we create a variable, we need to specify its type, or we can use the var keyword, which will be inferred as a specific type at compile time, these are called implicit variables.

In the case of dynamic variables, instead of determining their type at compile time, it is decided at runtime. 

 

 

2 - Using a dynamic type in programming

To declare a dynamic variable, it's as simple as using the dynamic keyword, the variable name, and assigning its value.

dynamic variableTest = 1;

Similarly, we can assign a string or any other type of value, as shown below.

dynamic variableTest = 1;
variableTest = “test”;

When the compiler processes the variable, what it does is convert it to the type Object in the vast majority of cases. 

This means that every time we assign a value to it, the type of the underlying object changes. You can see this using the following line of code:

dynamicVariable.GetType().ToString();

 

 

3 - Risks of using the dynamic type

When programming with the dynamic type, the compiler will not tell you if you are calling a method that accepts a specific type, nor will it tell you if you're accessing one of its properties correctly. 

So, just as the compiler won't tell you it's wrong, you could introduce errors into your code, which will only show up at runtime. 

To illustrate this, in the previous example we have the variable ejemploTest, which at this point is a string. We could try to access a property, for example .valor. As you can see, there's no error during compilation, but when you run it, you'll get an exception saying that the string type does not contain a property named valor.

Console.WriteLine(variableTest.Valor);

If we execute this example, we'll see how the compiler throws an exception

 

 

4 - Creating methods that accept dynamic types

For the same reason explained above, when you specify that the parameter type for a method is dynamic, it will accept any type of object you send, not just dynamic ones. 

However, as mentioned, you need to be careful when accessing its properties. 

 

 

5 - When to use dynamic types

Now here's the trickiest part, since everything mentioned so far makes it seem complicated, at least if you want to avoid errors, or you might ask "why should I use a dynamic type when I can use a specific type instead"

Keep in mind that, just as it has benefits, it also has drawbacks, so you shouldn't use it all the time as you would in JavaScript. 

Some scenarios where we might use dynamic include the following:

  • When writing code that communicates with another programming language.
  • When creating libraries for use in multiple languages.
  • When creating objects or methods and you don't care what type is coming in as input.
  • To create generic solutions.
  • It facilitates and simplifies working with reflection, which we will discuss later. 

And the downsides or cons you might encounter are:

  • It is notably slower than working with static types.
  • It increases the likelihood of errors at runtime.
  • Intellisense doesn't detect methods or properties, making them somewhat difficult to work with. 
This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café