I’m looking for a way to convert an object to one of several different types of structs. I need structs because I need it to be non-nullable. I’m not sure how to go about this, but this is what I’ve tried so far and it doesn’t work because:
“Object must implement IConvertible.” <- trying Convert.ChangeType
public class Something
{
private object[] things;
public Something()
{
//I don't know at compile time if this will
//be an array of ThingA's or ThingB's
things = new object[1];
things[0] = new ThingA();
ThingA[] thingsArrayA = GetArrayofThings<ThingA>();
things[0] = new ThingB();
ThingB[] thingsArrayB = GetArrayofThings<ThingB>();
}
public TData[] GetArrayofThings<TData>() where TData : struct
{
return (TData[])Convert.ChangeType(things, typeof(TData[]));
}
}
[Serializable]
public struct ThingA
{
//...
}
[Serializable]
public struct ThingB
{
//...
}
This is the working implementation thanks to Serg’s answer:
public TData[] GetArrayofThings<TData>() where TData: struct
{
return things.OfType<TData>().ToArray<TData>();
}
I’m still curious about any penalties for .ToArray() because this is data which will be sent to a stream object, and there could be a lot of it.
It seems to me that a few LINQ queries will suffice.
Don’t use
Convert, it’s for real conversion (e.g,stringtoint), and what you have is type casting.