-1

Is there a way to use a keyword as a parameter? I wanted to make a method called BytesToValue(), the way it would look is like this:

public static T BytesToValue<T>(byte[] buffer, T type)
{
    string retType = typeof(T).ToString();

    if (retType.Contains(".Byte"))
    {
        // code here.
    }
    else if (retType.Contains(".Int16"))
    {
       // code here.
    }
    // and so on with all other types.
}

I wanted the T type parameter to accept just a keyword e.g. BytesToValue(new byte[] { 0, 0, 0, 0 }, float), Is there a way to use keywords as parameters? I know the example wont work but is there a way to make it work? If not then what should i do?

Asdar
  • 125
  • 1
  • 5
  • 6
    Why even have that parameter? Its a generic method already. You have to pass the type to call it (i.e `BytesToValue(new byte[])`) – maccettura Mar 01 '18 at 18:09
  • Oh, didnt know you were able to do that. @maccettura Thanks for letting me know :) – Asdar Mar 01 '18 at 18:12

1 Answers1

6

You can even drop the second parameter and just use your generic type:

public static T BytesToValue<T>(byte[] buffer)
{
    Type type = typeof(T);

    if (type == typeof(byte))
    {
        // code here.
    }
    else if (type == typeof(short))
    {
       // code here.
    }

    // and so on with all other types.
}

Or you can let your string comparaisions if you feel like it or even use a switch case with types (C#7).

Haytam
  • 4,643
  • 2
  • 20
  • 43