class CustomClass where T: bool
{
public CustomClass(T defaultValue)
{
init(defaultValue); // why can\'t the compiler just use void init(bool) h
The compiler cannot use init(bool)
because at compile-time it cannot know that T
is bool
. What you are asking for is dynamic dispatch — which method is actually being called depends on the run-time type of the argument and cannot be determined at compile-time.
You can achieve this in C# 4.0 by using the dynamic
type:
class CustomClass
{
public CustomClass(T defaultValue)
{
init((dynamic)defaultValue);
}
private void init(bool defaultValue) { Console.WriteLine("bool"); }
private void init(int defaultValue) { Console.WriteLine("int"); }
private void init(object defaultValue) {
Console.WriteLine("fallback for all other types that don’t have "+
"a more specific init()");
}
}