tags:

views:

95

answers:

3

c#: How do I accept any kind of number into a function as an argument? Currently my AddDataInt32() asks specifically for Int32, but how I can accept any number, byte, ints signed or unsigned, so I can pass it on to BitConverter.GetBytes()? It's seems silly to write same funct's for each type :(

public void AddDataInt32(Int32 i)
{
    Data = ConcatTwoByteArrays(Data, BitConverter.GetBytes(i));
}
+2  A: 

Well, you could automate it with reflection and generics, but IMO overloads are the better choice - very much like your existing code.

Reflection / generics example - although I don't really recommend this route:

static void Main()
{
    byte[] bytes = GetBytes(123);
}
static byte[] GetBytes<T>(T value) {
    return Cache<T>.func(value);
}
static class Cache<T> {
    public static readonly Func<T, byte[]> func;
    static Cache() {
        MethodInfo method = typeof(BitConverter)
            .GetMethod("GetBytes", new Type[] { typeof(T) });
        if (method == null) {
            func = delegate { throw new ArgumentException(
                "No GetBytes implementation for " + typeof(T).Name); };
        } else { 
            func = (Func<T, byte[]>)Delegate.CreateDelegate(
                typeof(Func<T, byte[]>), method);
        }
    }
}

You would then mix that with an AddData<T> generic method that calls GetBytes<T> etc.

Marc Gravell
Nice answer Marc, but you might be overkilling it?
Dead account
Oh, absolutely ;-p
Marc Gravell
+1  A: 
public void AddData(object data )
{
}

or

public void AddData<T>( T data )
{
}

Although I think I would prefer overloaded methdos.

Frederik Gheysels
+4  A: 

You can just overload the method...

public void AddData (Int32 i)
{...}

public void AddData (Int16 i)
{...}

etc. One for each number type. When you make the call to the procedure, it will take any form of number that you've coded, with the same procedure name.

Tom Moseley
+1... you'd have to do this for all 10 overloads... yawn..
Dead account
Hey, that's what MS did for BitConverter, so that's probably your best bet.
Brian
I know it's a yawn, but it is, imo, the best way.
Tom Moseley
This is my preferred approach, as well.
Reed Copsey