Kayle
Kayle

Reputation: 65

Generic TypeCode Type Checking?

Should I avoid type checking with generics? Not using traditional type checking comparisons(myvar is int), but rather using the type's typecode.

Using generics, with type checking allows you to create a single method without parameters that supports the tasks of regular overloaded methods. This is a problem with parameter-less methods, they cannot be overloaded.

// "Buffer" is the byte[] while "Peek" is the read/write position. Then Align" is the alignment size in bytes of the buffer.
public type Read<type>() {
    switch( Type.GetTypeCode( typeof( type ) ) ) {
        case System.TypeCode.Boolean:
            bool bool_val = ( Buff[ Peek ] > 0 );
            Peek = ( ++Peek + ( Align - 1 ) ) & ~( Align - 1 );
            return (type)(object)bool_val;
        case System.TypeCode.Byte:
            byte byte_val = Buff[ Peek ];
            Peek = ( ++Peek + ( Align - 1 ) ) & ~( Align - 1 );
            return (type)(object)byte_val;
        case TypeCode.Ushort:
            ushort ushort_val = (ushort)( Buff[ Peek ] | ( Buff[ Peek + 1 ] << 8 ) );
            Peek += 2;
            Peek = ( Peek + ( Align - 1 ) ) & ~( Align - 1 );
            return (type)(object)ushort_val;
        break;
        ...
    }
}

This seems like the only way to achieve a form of overloading with parameter-less methods. Is this considered bad practice?

Upvotes: 5

Views: 890

Answers (1)

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29233

You can make your code generic with something like this:

var size = Marshal.SizeOf(typeof(T));
var subBuffer = new byte[size];
Array.Copy(Buff, Peek, subBuffer, 0, size);
var handle = GCHandle.Alloc(subBuffer, GCHandleType.Pinned);
var ptr = handle.ToIntPtr();
var val = (T)Marshal.PtrToStructure(ptr, typeof(T));
ptr.Free();
Peek += size;
Peek = ( Peek + ( Align - 1 ) ) & ~( Align - 1 );
return val;

However, if this suffers from performance issues for your use case, then providing hard-coded specialized versions probably isn't a bad way to do it, since there aren't any obvious alternatives.

Upvotes: 1

Related Questions