0

I've created a generic interface class and inherit from it with another generic class. The compiler doesn't like my function (see the error within the code).

What am I missing?

I'd like to create objects from ChecksumTruncate12Bit with types ushort, uint and ulong

public interface IChecksum<T>
{
    T Checksum(byte[] buffer, int size);
}

public class ChecksumTruncate12Bit<T> : IChecksum<T>
{
    public T Checksum(byte[] buffer, int size)
    {
        T rv = (T)0; // Error CS0030 Cannot convert type 'int' to 'T'

        for (int i = 0; i < size; ++i)
        {
            rv += (T)(buffer[i]); // Error CS0030 Cannot convert type 'byte' to 'T'
            rv &= (T)(0x0FFF); // Error CS0030 Cannot convert type 'int' to 'T'
        }

        return rv;
    }
}
teach me
  • 453
  • 5
  • 20
  • You have to specify the generic type parameter explicitly – Pavel Anikhouski Dec 05 '19 at 11:57
  • 3
    Well, the error says it all really. If I create a class called `Car` and use that in your class, what would you expect to happen here: `Car rv = (Car)0;` – Jamiec Dec 05 '19 at 11:57
  • 1
    C# doesn't have anything in the way of generic numerics. You'll have to pick a type and stick with it. You can use `default(T)` to substitute for `(T) 0`, but things like conversion, addition and and bitwise operators can't be captured with generic constraints. – Jeroen Mostert Dec 05 '19 at 11:59

1 Answers1

0

It does not make sense (nor is it possible) to make your ChecksumTruncate12Bit itself generic. It can still implement your generic interface, it just needs to specify the type - in this example uint:

public class ChecksumTruncate12BitUint : IChecksum<uint> 
{
    public uint Checksum(byte[] buffer, int size)
    {
        uint rv = 0; 

        for (int i = 0; i < size; ++i)
        {
            rv += (uint)(buffer[i]); 
            rv &= (uint)(0x0FFF); 
        }

        return rv;
    }
}

You can implement separately for ushort and ulong.

Jamiec
  • 133,658
  • 13
  • 134
  • 193