Mahdi Tahsildari
Mahdi Tahsildari

Reputation: 13582

Cast an object to IEnumerable<T> where I know what T is

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?

Upvotes: 0

Views: 160

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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.

Upvotes: 2

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

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>

Upvotes: 0

Related Questions