Home > Back-end >  Appropriate Use of Dynamic Keyword in C# with Templated Function
Appropriate Use of Dynamic Keyword in C# with Templated Function

Time:08-27

I am new to C#. I have read that the use of the keyword dynamic is somewhat controversial, and that other methods may be preferred depending on the use case. I want to make sure that my use of dynamic is appropriate for the language and the case. I'm working with this code:

public void myMethod(Action<T> myFunc) {
    dynamic arg = "example"; // a string
    myFunc(arg); 
}

I don't know what the type T will be until runtime, and so I thought that dynamic would be useful. In the event that T is a string, I want to invoke myFunc with that argument. Is using dynamic the best way to do this in C#?

edit: To give more context, if T is string, then I want to pass arg to myFunc. If I don't use dynamic, I get an error that "cannot convert from 'string' to 'T'". Using dynamic solves this problem, I'm just not sure if it's the best way to solve it.

CodePudding user response:

No. That is not an appropriate usage. You code will fail at runtime if T is anything other than string. That is the thing with dynamic, it turns of compiler checks, it does not mean your code will run, only that compiler errors turn into runtime errors. Dynamic is intended for interoperability with dynamic languages, or COM, where you are forced to cast objects at runtime anyway, so dynamic just makes it easier, without loosing any actual safety.

If you want to give myFunc a string, declare it as Action<string>. If you want to create a new object and give it to myFunc, add a new() restriction, i.e.

public void myMethod(Action<T> myFunc) where T : new(){
    myFunc(new T()); 
}

If you don't know how to construct T, let the caller give it to you:

public void myMethod(Action<T> myFunc, T value) {
    myFunc(value); 
}

You can also use Func<T> to give your method a delegate that constructs values on demand.

Also Action<T> would be called a "generic delegate". Even if c templates and c# generics are used for a similar purpose, they work in a very different way. In effect c# generics is more restrictive, but also makes compiling much faster and easier since you do not have to generate code for each specialization until it is jitted.

  • Related