John Bustos
John Bustos

Reputation: 19544

Return an inherited type from a method

Suppose I have the following classes defined:

Public Class BaseClass
    ...
End Class

Public Class DerivedClass
    Inherits BaseClass

   ... Extra Fields, methods, etc ...
End Class

And then, in my code, I have a function with a signature of:

Public Function DoSomething(...) As List(Of BaseClass)

And when I try and return an object of type List(Of DerivedClass) from it, I get the error:

Value of type 'System.Collections.Generic.List(Of BaseClass)' cannot be converted to 'System.Collections.Generic.List(Of DerivedClass)'

I know not all the extra fields of the DerivedClass will be filled, but it would give me what I needed.

Is there a way to do this, or is this just considered bad programming practice? And, if so, what would be the right way to do this?

Upvotes: 1

Views: 134

Answers (1)

Ian P
Ian P

Reputation: 12993

Have a look at this:

http://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx

Understanding Covariance and Contravariance will clear things up a bit :)

  • Covariance

Enables you to use a more specific type than originally specified. You can assign an instance of IEnumerable (IEnumerable(Of Derived) in Visual Basic) to a variable of type IEnumerable.

Example:

IEnumerable<Derived> d = new List<Derived>();
IEnumerable<Base> b = d;
  • Contravariance

Enables you to use a more generic (less derived) type than originally specified. You can assign an instance of IEnumerable (IEnumerable(Of Base) in Visual Basic) to a variable of type IEnumerable.

Example:

Action<Base> b = (target) => { Console.WriteLine(target.GetType().Name); };
Action<Derived> d = b;
d(new Derived());
  • Invariance

Means that you can use only the type originally specified; so an invariant generic type parameter is neither covariant nor contravariant. You cannot assign an instance of IEnumerable (IEnumerable(Of Base) in Visual Basic) to a variable of type IEnumerable or vice versa.

Upvotes: 2

Related Questions