C# generics when T could be an array
Posted
by bufferz
on Stack Overflow
See other posts from Stack Overflow
or by bufferz
Published on 2010-04-21T14:47:51Z
Indexed on
2010/04/21
15:03 UTC
Read the original article
Hit count: 261
I am writing a C# wrapper for a 3rd party library that reads both single values and arrays from a hardware device, but always returns an object[] array even for one value. This requires repeated calls to object[0] when I'd like the end user to be able to use generics to receive either an array or single value.
I want to use generics so the callee can use the wrapper in the following ways:
MyWrapper<float> mw = new MyWrapper<float>( ... );
float value = mw.Value; //should return float;
MyWrapper<float[]> mw = new MyWrapper<float[]>( ... );
float[] values = mw.Value; //should return float[];
In MyWrapper I have the Value property currently as the following:
public T Value
{
get
{
if(_wrappedObject.Values.Length > 1)
return (T)_wrappedObject.Value; //T could be float[]. this doesn't compile.
else
return (T)_wrappedObject.Values[0]; //T could be float. this compiles.
}
}
I get a compile error in the first case:
Cannot convert type 'object[]' to 'T'
If I change MyWrapper.Value to T[] I receive:
Cannot convert type 'object[]' to 'T[]'
Any ideas of how to achieve my goal? Thanks!
© Stack Overflow or respective owner