generic parameter overloading

Hey guys!

First I'm not entirely sure if this goes into this forum, never the less.
I'm wondering why not allow code as the following:

public I MyFunc<I>(I param)
where I : Interface1
{
}

public I MyFunc<I>(I param)
where I: Interface2
{
}

As far as I can see this would work exactly as function overloading with the arguments:

public void MyFunc(Interface1 param)
{
}

public void MyFunc(Interface2 param)
{
}

This seems to be a matter of the compiler, as it doesn't seem to be impossible to incorporate into a future version of the compiler. Similar to how java does it.



Answer this question

generic parameter overloading

  • sofakng

    Yeh, for now it does work to have a workaround like this:

    public interface Interface1<RealT> {}
    public interface Interface2<RealT> {}

    public static I MyFunc<I>(Interface1<I> param)
    where I: Interface1<I>
    {
    }

    public static I MyFunc<I>(Interface2<I> param)
    where I: Interface2<I>
    {
    }

    Though it gets ugly real fast :S


  • Alvin Kuiper

    Hi, bilsa

     bilsa wrote:


    public I MyFunc<I>(I param)
      where I : Interface1
    {
    }

    public I MyFunc<I>(I param)
      where I: Interface2
    {
    }

    In this situation,

    Imagine that if one instance of a class which implement Interface1 as well as Interface2 has been past to MyFunc, which should be choosed How can we decide to call the previous one or the other one

    So, it is vague syntax. For this reason compiler surely cant allow this thing to happen.

     bilsa wrote:


    public void MyFunc(Interface1 param)
    {
    }

    public void MyFunc(Interface2 param)
    {
    }


    In this way, the syntax is right, because you emplicitly show the interface name (Interface1 param or Interface2 param).

    So, your calling MyFunc((Interface1)obj) is different from MyFunc((Interface2)obj).

    Hope it is clear.

    If you have further questions, pls feel free to let me know.

    Thank you

     



  • vkan

    Yes this is a limitation of the current implementation of the generics. They have a few other limitations too, btw. You should report this in connect: http://connect.microsoft.com/VisualStudio - Report it as a request for a future version. I have posted there a few things about generics too.

    There are a few things that are possible in the CLR but not accessible from different languages. You could for example (in the CLR) overload a method by specifying a different return type. That is, for example, not supported by the C# compiler, although the runtime would support it.



  • generic parameter overloading