views:

49

answers:

3

I have a business object class BusinessObject which implements an interface IAlternateInterface. I already have a method that will return a generic list of BusinessObject which has the objects I want but I want to get them as a list of IAlternateInterface. I tried to do something like the following psudo code but I am getting a "Can not convert source type ... to target type ..." message in Visual Studio. What is the best way to convert the list?

public List<BusinessObject> GetObjects(){
 //logic to get the list
}

public List<IAlternateInterface> GetInterfaceObjects(){
 return GetObjects();
}
+2  A: 

You're looking for Enumerable.Cast<TResult>:

GetObjects().Cast<IAlternateInterface>.ToList();

The ToList at the end is only necessary if you need a list. Cast<TResult> returns an IEnumerable<TResult>

Rob
I threw the code in my project real quick to and this compiles so I'm sure it will work. I'll play with it on Monday to make sure but I'm fairly certain this will do what I need it to. Thank you and the other people who answered.
William
A: 

With LINQ Cast

public List<IAlternateInterface> GetInterfaceObjects(){
 return GetObjects().Cast<IAlternateInterface>().ToList();
}
Jesper Palm
+2  A: 

The two answers given using Cast are fine for C# 3 and C# 4... but if you're using C# 4 (and .NET 4) you can also use generic variance to avoid one step:

public List<IAlternateInterface> GetInterfaceObjects(){
  return GetObjects().ToList<IAlternateInterface>();
}
Jon Skeet
The OP is getting "Can not convert source type to target type", so it may not be C# 4. But in that case, wouldn't `return GetObjects();` work here as well?
Kobi
@Kobi: Nope, because `List<T>` is invariant. You'd still need to build a `List<IAlternativeInterface>` which the call to `ToList` will do - but it will use the implicit conversion of `List<BusinessObject>` to `IEnumerable<IAlterantiveInterface>` which is now available.
Jon Skeet
Oh, of course! So maybe a clean solution here is to return `IEnumerable<IAlterantiveInterface>`, but that depends on that the OP needs... Thanks.
Kobi
@jon: that's nice, haven't gotten to that chapter in your book yet :)
Rob