Home > front end >  Convert decimal to binary with reflection and generics in the static Convert class?
Convert decimal to binary with reflection and generics in the static Convert class?

Time:09-17

I'm trying to make a static generic function to convert decimal (numeric type) to a binary string.

Let me explain. I know that what I have to do is this:

int number = 12;
string binaryString = Convert.ToString(number, 2);

This is simple, but I also want to make the convertion decimal to binary with other parameters types, like bytes, shorts(Int16), longs(Int64). I know that Convert.Tostring() have all of the overloads for that and I simple need to do overloads like:

public static string DecToBinary(short number)
{
   return Convert.ToString(number, 2);
}

public static string DecToBinary(long number)
{
   return Convert.ToString(number, 2);
}
//etc

But I want to make it with generics and reflection... So I tried this:

public static string DecToBinary<T>(T number) where T : struct, IComparable, IFormattable, IConvertible
{
   return (string)typeof(Convert).GetMethod("ToString").Invoke(null, new object[] { number, 2 });
}

But I'm getting a problem on runtime that say:

Ambiguous match found.

and make sense, since reflection use a object as parameter type and never know what type I want...

Anyone can help me solve this problem?

CodePudding user response:

Check the overloads of Type.GetMethod() which allow you to provide an array of parameter types (Type[]). This should help the CLR resolve the correct overload of the Convert.ToString() method.

  • Related