Dave
Dave

Reputation: 411

C# Generics issue: some invalid arguments

public class ImgBuffer<T>
{
    public T[] buf;
    public int width;
    public int height;
    public ImgBuffer () {}
    public ImgBuffer (int w, int h)
    {
        buf = new T[w*h];
        width = w;
        height = h;
    }

    public void Mirror()
    {
        ImageTools.Mirror (ref buf, width, height);
    }
}

And the ImageTools class has Mirror defined for byte[], short[], and Color32[] on the fist argument. In particular:

public void Mirror(ref Color32[] buf, int width, int height) { ....

But I get this error:

error CS1502: The best overloaded method match for `ImageTools.Mirror(ref Color32[], int, int)' has some invalid arguments

What am I doing wrong?

Upvotes: 1

Views: 613

Answers (2)

Anthony Pegram
Anthony Pegram

Reputation: 126982

It looks like you expect C# generics to be something like a template. That's not the case. From your description, it appears there is an ImageTools class that looks something like this

public class ImageTools
{
    public static void Mirror(ref byte[] buf, int width, int height) { }
    public static void Mirror(ref Color32[] buf, int width, int height) { }
    public static void Mirror(ref short[] buf, int width, int height) { }
}

And you have an ImgBuffer class that looks like this (abbreviated)

public class ImgBuffer<T>
{
    public T[] buf;
    public int width;
    public int height;

    public void Mirror()
    {
        ImageTools.Mirror(ref buf, width, height);
    }
}

The compiler cannot verify in ImgBuffer.Mirror that the call to ImageTools.Mirror is legal. All the compiler knows about ref buf is that it is of type T[]. The T could be anything. It could be string, int, DateTime, Foo, etc. The compiler is unable to verify that the arguments are correct, and therefore your code is illegal.

This would be legal, but I have a feeling that you have specific implementations for your Mirror methods for your 3 desired types, so it's probably not workable.

public class ImageTools<T>
{
    public static void Mirror(ref T[] buf, int width, int height) { }
}

Upvotes: 4

Dessus
Dessus

Reputation: 2177

You need to scope your generic type argument. For example:

public class ImgBuffer<T> where T : Color32
{
    public T[] buf;
    public int width;
    public int height;
    public ImgBuffer () {}
    public ImgBuffer (int w, int h)
    {
        buf = new T[w*h];
        width = w;
        height = h;
    }

    public void Mirror()
    {
        ImageTools.Mirror (ref buf, width, height);
    }
}

Upvotes: 0

Related Questions