for example in c#
void Foo(object obj){
Do(obj);
}
void Do(T1 obj){}
void Do(T2 obj){}
void Do(T3 obj){}
How can I implement that the Foo function can choose correct Do function to perform obj without using switch or if?
for example in c#
void Foo(object obj){
Do(obj);
}
void Do(T1 obj){}
void Do(T2 obj){}
void Do(T3 obj){}
How can I implement that the Foo function can choose correct Do function to perform obj without using switch or if?
If you don't want if
or switch
or cast or pattern matching,
you can use dynamic
.
Not best practice, likely, but works.
void Foo(object obj){
dynamic value = obj;
Do(value); // will throw if obj is not T1 T2 or T3
}
No way. When the type isn't known at compile-time, you have to do runtime-checks and pick the correct method with if/switch.
The only option, to use it without a switch/if is to call Do()
directly with correct type.
T1 obj = new T1();
// compiler knows the type and can choose the correct method
yourClass.Do(obj);
There is a other way with the dynamic
"type".
I didn't accept it as solution, because it bypass all the type-safety at compile-time. It can lead to a very unexpected behavior on runtime.
As a example: If you remove one overload Do(T1 obj)
and make a call with T1
, then you will get an error on runtime (not at compile-time).
T1 obj = new T1();
yourClass.Foo(obj); // <-- this will work at compile-time
// but in runtime, it will end up in a excpetion
// even worse, the compiler is now happy with these bad calls
yourClass.Foo("it accepts a string");
yourClass.Foo(123); // and numbers
And it also introduces a very bad performance.
For more information, look here: Is the use of dynamic considered a bad practice?
AFAIK, you need to specify what the type is so that the correct Do()
can be called. Maybe something like (I have no idea if this would work tho)
Do((obj as T1)?? (obj as T2)?? (obj as T3));