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!