Daily Knowledge Drop
The dynamic
type can be used in the use case when required to call into a generic method, from a non-generic method. This is a fairly niche use case, but when required, the dynamic
technique explained below can be of great benefit.
Generic method
Assume we have the following simple generic method:
public static void GenericMethod<T>(T parameter)
{
Console.WriteLine($"T is of type: {typeof(T).Name}");
}
This method needs to be called from another non-generic method which contains an object
variable.
Object technique
Calling into the generic method with an object
:
public static class Converter
{
public static void ObjectMethod(object randomObj)
{
// call into the generic method with the
// object type
GenericMethod(randomObj);
}
}
While this will compile and "work", calling the ObjectMethod
method with various types, will result in the same output:
Converter.ObjectMethod("string value");
Converter.ObjectMethod(1001);
The output:
T is of type: Object
T is of type: Object
As an Object
is being passed to the generic method (even though the underlying types are different), the values are boxed into that type, and that is what is output.
If we would like to know the actual type output, then the dynamic technique
can be used.
Dynamic technique
The dynamic technique
involves casting the object to dynamic
before calling the generic method:
public static class Converter
{
public static void ObjectMethod(object randomObj)
{
// cast the object to dynamic
dynamic dynObj = randomObj;
GenericMethod(dynObj);
}
}
Now, calling the generic method with the same variables:
Converter.ObjectMethod("string value");
Converter.ObjectMethod(1001);
Will result in the following output:
T is of type: String
T is of type: Int32
Notes
A fairly niche use case, and a small difference in code but one which can make a big difference when the use case is encountered. There might be a performance impact with the dynamic technique (as dynamic generally is less performant), but this might be out-weighed by the benefit the technique gives. As always, if performance is an issue, benchmark and and make an informed decision which technique to use.
References
Daily Drop 236: 17-01-2023
At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.
The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.