In asking this previous question, I was given an answer that I know is correct, but I still have (saldy) no clue how to implement it...
Suppose I have the following code:
Public Class BaseClass
...
End Class
Public Class DerivedClass
Inherits BaseClass
... Extra Fields, methods, etc ...
End Class
And, then, in another procedure, I have the following function defined:
Public Function DoSomething(i as Integer, s as String, b as Boolean) As List(Of BaseClass)
...
End Function
And am using it to TRY and return both List(Of BaseClass)
and List(Of DerivedClass)
in my procedure, but have no clue how to do it - Even though, now I'm pretty sure (thanks to the answer to my previous question) that it would involve a delegate function call.
Could someone please show me what that code would look like?
Also, although I'm more comfortable with VB.Net, I understand C# well enough to be able to make the conversion, so either solution would be GREATLY apprecieted.
Thank you!!
EDIT:
Based upon the feedback from @Servy in his answer below, I understand that this is not about creating a Delegate function, but rather about Returning an IEnumerable(OF BaseClass)
from my function than a List(Of BaseClass)
. So, I changed it, but it's still not working...
I now understand why, but don't know what to do about it...
Current code:
Public Function DoSomething(i as Integer, s as String, b as Boolean) As IEnumerable(Of BaseClass)
Dim RetVal as New List(Of BaseClass)
Dim ToAdd as BaseClass
... some code ...
... loop
Retval.Add(ToAdd)
...
Return RetVal
End Function
Now, I cannot change RetVal
in my code to an IEnumerable
since then Add
is not allowed.
How do I do what I'm trying to do here?
THANK YOU!!!
The type
List<T>
is not covariant with respect toT
, so what you want is not possible. To leverage covariance you'll need to use a type that supports it, such asIEnumerable<T>
.While delegates can themselves leverage covariance, they still require the types in question to support it. They will do nothing to allow you to treat
List<T>
as being covariant.