Thursday, April 28, 2011

How to accept any kind of number into a function as an argument in C#?

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));
}
From stackoverflow
  • 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.

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

    or

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

    Although I think I would prefer overloaded methdos.

  • 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.

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

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.