2

I have the following problem:

There are several color interfaces with a base interface IColor.

public interface IColor { }
public interface IColor3 : IColor { }
public interface IColor4 : IColor { }

Some algorithms support processing only on some color types:

    public static Image<TColor, byte> Bla<TColor>(this Image<TColor, byte> img, bool inPlace = true)
        where TColor : IColor4
    {
       //do something
    }

    public static Image<TColor, byte> Bla<TColor>(this Image<TColor, byte> img, bool inPlace = true)
        where TColor : IColor3
    {
       //do something
    }

When I try to compile I get an error that a function with the same parameters is already defined. How can I resolve this ?

M4N
  • 94,805
  • 45
  • 217
  • 260
dajuric
  • 2,373
  • 2
  • 20
  • 43
  • 2
    See the following blog post: [Generic constraints are not part of the method signature](http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx) – John Rasch Feb 18 '14 at 21:11
  • @MarcinJuraszek, John Rasch: Thank you very much – dajuric Feb 18 '14 at 21:15

3 Answers3

7

The overload of methods is based in parameters and name only. That means you write a replicated method not a overload.

I Suggest to you edit the code for this:

public static Image<IColor4, byte> Bla(this Image<IColor4, byte> img, bool inPlace = true)
{
   //do something
}

public static Image<IColor3, byte> Bla(this Image<IColor3, byte> img, bool inPlace = true)
{
   //do something
}

Or:

public static Image<TColor, byte> Bla<TColor>(this Image<TColor, byte> img, bool inPlace = true)
    where TColor : IColor
{
    if(TColor == typeof(SomeSpecificType))
    {
        // do something specific here.
    }
}
Jonny Piazzi
  • 3,684
  • 4
  • 34
  • 81
1

In order to make this work, you would need two distinct (but potentially similar) generic classes

public static Image4<TColor, byte> Bla<TColor>(this Image<TColor, byte> img, bool inPlace = true)
    where TColor : IColor4
{
   //do something
}

public static Image3<TColor, byte> Bla<TColor>(this Image<TColor, byte> img, bool inPlace = true)
    where TColor : IColor3
{
   //do something
}

Also depending on what you want. These two classes could inherit from a common base that does whatever common functionality which can be performed on type IColor

jstromwick
  • 1,206
  • 13
  • 22
0

As stated in comments, the example you provided does not actually constitute method overloading, because method overloading is based on the method signature, which consists of the parameters only.

You can just use one method and test for the interfaces which derive from IColor within

public static Image<TColor, byte> Bla<TColor>(this Image<TColor, byte> img, bool inPlace = true)
    where TColor : IColor
{
    if (img is IColor3)
    {
        //do something
    }
    if (img is IColor4)
    {
        //do something
    }
}
Dmitriy Khaykin
  • 5,238
  • 1
  • 20
  • 32