I've got a method that receives an Object[] and then performs actions on that array.
At first I was passing in this array as an IEnumerable<T> however the T can be of two different types.
The T's will always have the same properties, even thought they're different types.
Is it possible to cast to a a type at runtime so that I can used the properties i know each one will contain?
So where as it's possible to do:
var dataObject = (IEnumerable<T>) dataArray;
Is it somehow possible to do:
var dataObject = (dataArray.GetType()) dataArray;
Are you able to modify the source code of the two T types? If so then you could make both of them either (a) inherit from a common base class or (b) implement a common interface.
Edit following comments...
To accomodate different types for the ID property you could use explicit interface implementation. This would allow you to expose the second object's ID as an Int64 when accessed via the common interface. (The ID property would remain accessible as an Int32 when not accessed through the interface.)
Unfortunately the explicit interface implementation will require more changes to your original types.
void YourMethod(IEnumerable<ICommonToBothTypes> sequence)
{
foreach (var item in sequence)
{
Console.WriteLine(item.ID);
}
}
// ...
public interface ICommonToBothTypes
{
long ID { get; }
}
public class FirstType : ICommonToBothTypes
{
public long ID
{
get { return long.MaxValue; }
}
}
public class SecondType : ICommonToBothTypes
{
// the real Int32 ID
public int ID
{
get { return int.MaxValue; }
}
// explicit interface implementation to expose ID as an Int64
long ICommonToBothTypes.ID
{
get { return (long)ID; }
}
}
You can just create it as an interface and have both of those classes implement the interface. Then take Interface[] as the parameter instead of Object and you avoid casting all together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With