Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#'s equivalent of Java's <? extends Base> in generics

In Java, I can do the following: (assume Subclass extends Base):

ArrayList<? extends Base> aList = new ArrayList<Subclass>(); 

What is the equivalent in C# .NET? There is no ? extends keyword apparently and this does not work:

List<Base> aList = new List<Subclass>(); 
like image 636
Louis Rhys Avatar asked Jan 19 '11 06:01

Louis Rhys


People also ask

What do you mean by C?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


2 Answers

Actually there is an Equivalent(sort of), the where keyword. I don't know how "close" it is. I had a function I needed to do something similar for.

I found an msdn page about it.

I don't know if you can do this inline for a variable, but for a class you can do:
public class MyArray<T> where T: someBaseClass
or for a function
public T getArrayList<T>(ArrayList<T> arr) where T: someBaseClass

I didn't see it on the page but using the where keyword it might be possible for a variable.

like image 67
Raystorm Avatar answered Oct 04 '22 13:10

Raystorm


Look into Covariance and Contravariance introduced with .Net 4.0. But it only works with interfaces right now.

Example:

IEnumerable<Base> list = new List<SubClass>(); 
like image 40
decyclone Avatar answered Oct 04 '22 11:10

decyclone