Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# polymorphism in Generic types

class Base
{}

class Sub : Base
{}


void AddNewBase(Base t, LinkedList<Base> list){ ... }
...
{

    Sub asub = new Sub();

    LinkedList<Sub> asubList = new LinkedList<Sub>();
    AddNewBase(asub,asubList) // doesn't work
}

basically, I have a custom insert function that takes a new item and a list to put it in, and it does some 'sorting' stuff to find a good place to put it in the list.

problem is, I want to do this based on properties in 'Base' so it would be good to have just one function that could do this for all lists of sub types.

I think what I kind of want is:

static void AddNewBase<T>(T t, LinkedList<T> list){ ... }

but with some way of clarifying T like: 'where T is a sub class of Base'

like image 900
matt Avatar asked Nov 11 '10 13:11

matt


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is C full form?

History: The name C is derived from an earlier programming language called BCPL (Basic Combined Programming Language). BCPL had another language based on it called B: the first letter in BCPL.


1 Answers

You can declare Constraints on Type Parameters:

static void AddNewBase<T>(T t, LinkedList<T> list) where T : Base { ... }
like image 122
dtb Avatar answered Oct 27 '22 06:10

dtb