Member with the same signature already defined with type restrictions

I ran into a problem with overload methods that have different limitations that seem exclusive. This is my example:

public class A
{
    public void Do<T>() where T : class
    {

    }

    public void Do<T>() where T : struct 
    {

    }
}

And this does not compile with the following error: "Member with the same signature that is already defined." Is it possible to fulfill both conditions at once or is it just a limitation of the C # compiler?

+5
source share
3 answers

This is not a compiler constraint - it is a language constraint (and quite possibly the CLR, I'm not sure).

These are mostly conflicting overloads - this is similar to trying to overload by return type. It is not supported.

You can declare methods so that these calls are compiled for calls to different methods:

a.Do<int>();
a.Do<string>();
a.Do<int?>();

... / , horrible.

, , , "arity" ( ):

public void Foo() {}
public void Foo<T>() {}
public void Foo<T1, T2>() {}
+8

, . .

+2

:

A.Do``1

.

, , , :

public class A
{
    public void Do<T>()
    {
        if(typeof(T).IsValueType){
            // nasty reflection to call DoValueType
        }
        else {
            // nasty reflection to call DoReferenceType
        }
    }
    private void DoReferenceType<T>() where T : class {

    }
    private void DoValueType<T>() where T : struct {

    }
}
+1

All Articles