Questions tagged [generics]

Generics are a form of parametric polymorphism found in a range of languages, including .NET languages, Java, Swift, Rust and Go (since 1.18).

is a language feature found in certain languages to enable a form of . They typically allow the programmer to express concepts such as "A list of some type T" in a type-safe manner. Prior to the addition of generics to the language and the , programmers using these languages were forced to downcast from the base Object when using some general purpose classes, such as collection classes.

With the addition of , the programmer can instead use types such as List<int> to create type-safe lists which only store int objects.

In-depth detail for examples and concepts specifically for C# Generics is provided by Microsoft here. Information on Java generics can be found here.

Unlike , generics are typically limited to simple type substitution, without the ability of templates to specialize in specific types (infamously misused in the C++ standard library in std::vector<bool> which behaves radically different from any other std::vector<T>). This also means that generics are not well suited for , which typically relies on an ability to tailor generic algorithms for specific parameter types (again using a C++ example, pointers are usable with any generic algorithm expecting arguments to be iterators).

Java Generics Tutorials

  1. Java Generic methods and generic classes Tutorials
  2. Java Generics FAQs

.NET Generics Tutorials

  1. Introduction to Generics
  2. C# Generics

Rust Generics Tutorials

  1. Generics chapter from The Rust Book
  2. Generics section from Rust By Example

Go Generics Tutorials

  1. Tutorial: Getting started with generics

Example

C# without Generics

var list = new System.Collections.ArrayList();
list.Add(1);
list.Add("banana"); // will compile

int n = (int) list[0];
int s = (int) list[1]; // will compile, but throws an InvalidCastException

C# with Generics

var list = new System.Collections.Generic.List<int>();
list.Add(1);
//list.Add("banana"); -- Will not compile

int n = list[0];
//string s = list[1]; -- will not compile
49056 questions
20
votes
3 answers

C# interface specfying a generic return type

I have something like: public interface IExample { int GetInteger() T GetAnything(); //How do I define a function with a generic return type??? ^^^^^ } Is this possible???
River
  • 1,487
  • 3
  • 15
  • 25
19
votes
3 answers

C# : Get type parameter at runtime to pass into a Generic method

The generic Method is... public void PrintGeneric2(T test) where T : ITest { Console.WriteLine("Generic : " + test.myvar); } I'm calling this from Main()... Type t = test2.GetType(); PrintGeneric2(test2); I…
user1229895
  • 2,259
  • 8
  • 24
  • 26
19
votes
2 answers

Reflexive type parameter constraints: X where T : X ‒ any simpler alternatives?

Every so often I am making a simple interface more complicated by adding a self-referencing ("reflexive") type parameter constraint to it. For example, I might turn this: interface ICloneable { ICloneable Clone(); } class Sheep : ICloneable { …
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
19
votes
5 answers

Sort Generic list on two or more values

We have a generic List(Of Product) that must be sorted on two or more properties of the Product class. The product class has the properties "Popular" numeric (asc), "Clicked" numeric (desc), "Name" string (asc). In order of naming the properties, we…
Bas
19
votes
3 answers

How to make an Excel-Like Sort By A, Then By B in a TObjectList<> using multiple comparers

I have just started to use generics, and I am currently having a problem doing sorting on multiple fields. Case: I have a PeopleList as a TObjectList and I want to be able to make an Excel-like sorting function, by selecting one sort-field…
TechnoCowboy
  • 344
  • 2
  • 15
19
votes
3 answers

Returning original collection type in generic method

Say we want to make a function like minBy that returns all elements of equal minimalism in a collection: def multiMinBy[A, B: Ordering](xs: Traversable[A])(f: A => B) = { val minVal = f(xs minBy f) xs filter (f(_) == minVal) } scala>…
Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
19
votes
2 answers

Filtering lists of generic types

Lists or Iterables can be filtered easily using guavas filter(Iterable unfiltered, Class type). This operation performs two tasks: the list is filtered and transformed into a sequence of the given type T. Quite often however I end up with…
Ditz
  • 735
  • 7
  • 17
19
votes
2 answers

Equivalent of TreeSet in Java to C#.net

I have Java code containing a TreeSet. I want to convert the code to C#. Which equivalent collection can I use? If there is none please suggest alternatives.
usr021986
  • 3,421
  • 14
  • 53
  • 64
19
votes
5 answers

Specifying the return type of an abstract method from a Base Class according to a Sub Class

I have the following structure: abstract class Base { public abstract List<...> Get(); //What should be the generic type? } class SubOne : Base { public override List Get() { } } class SubTwo : Base { public…
Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
19
votes
5 answers

Java generics with 'semantics', is this possible?

Firstly apologies if I'm using the wrong term by picking the word 'semantics.' I'm a big fan of generics in Java for all the obvious reasons. It helps me enormously as I work with a huge variety of odd bits of code and I often have to go back to old…
Tim
  • 5,024
  • 2
  • 30
  • 58
19
votes
5 answers

Java generics parameter bounding to any of a range of types

Is there a syntax or workaround to constrain a generic type parameter to any of a range of types? I am aware that you can constrain a type to be all of a range of types (ie AND logic): public class MyClass & Serializable> { }…
Bohemian
  • 412,405
  • 93
  • 575
  • 722
19
votes
6 answers

Calling a static method using generic type

No static member can use a type parameter, but is it possible to call a static member using the generic type parameter? For example:- abstract class Agent{ void callAgent(); Agent(){ A.add(); } } Here…
aps
  • 2,452
  • 10
  • 35
  • 47
19
votes
8 answers

Entity Framework - how do I get the columns?

I wish to get a list of columns names, types and whether the column is a PK of a table object in Entity Framework. How do I do this in C# (4.0) (ideally generically)? The winning answer will be one that does it efficiently and most importantly…
Dan B
  • 936
  • 2
  • 13
  • 26
19
votes
4 answers

Why does this generics scenario cause a TypeLoadException?

This got a bit long-winded, so here's the quick version: Why does this cause a runtime TypeLoadException? (And should the compiler prevent me from doing it?) interface I { void Foo(); } class C { public void Foo() where T2 : T1 {…
Igby Largeman
  • 16,495
  • 3
  • 60
  • 86
19
votes
2 answers

Converting List to byte[]

How can I take a List and turn it into a byte array. I thought there might be some clever LINQ options for it but am unsure eg/List.ForEach
Jon
  • 38,814
  • 81
  • 233
  • 382