Question

I'm attempting to write a method that can accept any type of variable, convert it to a string showing its hexadecimal representation and output based on a generic type.

To clarify, I want to:

  • Accept a T variable (int, string, byte[], double, etc)
  • Convert to hexadecimal ( string "bacon" == "6261636F6E" )
  • Output as T type. (I'm aiming for using this for byte[] and string)

Currently I'm only testing with passing in a string & having the method return either a byte array or a string.

The Call:

string sqliteEncKey = "bacon";

string return = ConvertToHexString<string>( sqliteEncKey );
AND/OR
byte[] return = ConvertToHexString<byte[]>( sqliteEncKey ); // type mismatch issue.

And the method:

public static T ConvertToHexString<T>( this T _input ) {
    string hexString = "";

    switch ( Type.GetTypeCode( _input.GetType() ) ) {
        case TypeCode.String:
            foreach( char c in _input.ToString() ) {
            int tmp = c;

            hexString += String.Format( "{0:x2}", (uint)System.Convert.ToUInt32( c.ToString() ) );
        }
        break;
    default:
        hexString = null;
        break;
    }

    return (T)Convert.ChangeType( hexString, typeof(T) );
}

My problem is that in trying to make the return type dynamic I seem to be messing with the parameter as well. Can I specify the type of the variable being passed in separately to the return type?

Many thanks in advance!

Was it helpful?

Solution

Yes, you can just use two generic parameters:

public static TRet ConvertToHexString<TVal, TRet>( this TVal _input ) {

However, if you're inspecting the type of the input value as you are in that case statement, you're pretty much defeating the purpose of using generics and are probably better off using specific types:

public static TRet ConvertToHexString<TRet>( this string _input ) {

public static TRet ConvertToHexString<TRet>( this byte[] _input ) {

etc.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top