Generics Question

S

Steve Drake

Hello,

I may be mis understanding some of the uses of generics so this example may
not be valid, but here goes.

I have a method that I wont to be able to return a string or byte array, it
declared as :

public T Decrypt<T>(byte[] cipherText, byte[] optionalEntropy)

how do I know what type T is, I want todo something like :

if (T is string )
{
return (T)(object)Encoding.ASCII.GetString(plainText);
}
else
{
return (T)(object)plainText;
}


Also, I want to limit T to string or byte[], can this be done.

Steve
 
D

Daniel O'Connell [C# MVP]

Steve Drake said:
Hello,

I may be mis understanding some of the uses of generics so this example
may not be valid, but here goes.

I have a method that I wont to be able to return a string or byte array,
it declared as :

public T Decrypt<T>(byte[] cipherText, byte[] optionalEntropy)

how do I know what type T is, I want todo something like :

if (T is string )
{
return (T)(object)Encoding.ASCII.GetString(plainText);
}
else
{
return (T)(object)plainText;
}

The typeof operator can be used on generic type parameters, meaning
typeof(T) == typeof(string) if the parameter is string.
Also, I want to limit T to string or byte[], can this be done.

No, you'd probably be best off writing a common method that does all the
grunt work and a companion method that converts it to a string:

byte[] Decrypt(byte[] cipherText, byte[] optionalEntropy);
string[] DecryptString(byte[] cipherText, byte[] optionalEntropy)
{
byte[] plainText = Decrypt(cipherText,optionalEntropy);
return Encoding.ASCII.GetString(plainText);
}

This is probably easier for the end user to understand and doesn't give you
any issues when someone passes System.Windows.Forms.ListBox as the type
parameter.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top