0

I have an object which is containing an IEnumerable where T can be among a couple of Classes I have in my Data Model.

Let's say T can be either Employee or Employer. Now having a bare object, knowing that it is certainly holding an IEnumerable how Can I say which Type it is holding? Employee or Employer? Or better how can I cast or reflect the object to IEnumerable?

If I keep the type when I set the object, will it help me cast or reflect the object to what it was at first?

If I keep these

object source = db.Employees; //IEnumerable<Employee>
type dataType = Employee;

can I cast or reflect back to an IEnumerable of Employees?

Mahdi Tahsildari
  • 13,065
  • 14
  • 55
  • 94

2 Answers2

2

In general case you can use Reflection:

Type typeOfSource = source.GetType().GetGenericArguments()[0];

if (typeOfSource == typeof(Employee)) {
  ...
}
else if (typeOfSource == typeof(Employer)) {
  ...
}

it's an overshoot in a simple case with two types only, but can be useful if you have a really entangled code.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

tYou can try the as operator

var otherEmployess = source as IEnumerable<Employee>;

if(otherEmployess != null)
{
        // use otherEmployees
}

Alternatively you can case to IEnumerable<Employee> but that will throw an exception if the type is not IEnumerable<Employee>

NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61
  • I would imagine that `db.Employees` would always be an `IEnumerable`, so why the safe cast? I think the OP may just not know how to perform a cast in general. – Ed S. May 05 '14 at 05:37