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
1602
votes
24 answers

How to Sort a List by a property in the object

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class: List objListOrder = new List(); GetOrderList(objListOrder); // fill list of orders I want to sort the…
Shyju
  • 214,206
  • 104
  • 411
  • 497
1414
votes
22 answers

Create Generic method constraining T to an Enum

I'm building a function to extend the Enum.Parse concept that Allows a default value to be parsed in case that an Enum value is not found Is case insensitive So I wrote the following: public static T GetEnumFromString(string value, T…
johnc
  • 39,385
  • 37
  • 101
  • 139
1280
votes
9 answers

How do I use reflection to call a generic method?

What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime? Consider the following sample code - inside the Example() method, what's the most concise way to invoke…
Bevan
  • 43,618
  • 10
  • 81
  • 133
1230
votes
32 answers

How to create a generic array in Java?

Due to the implementation of Java generics, you can't have code like this: public class GenSet { private E a[]; public GenSet() { a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation } } How can I implement…
tatsuhirosatou
  • 25,149
  • 14
  • 39
  • 40
1034
votes
14 answers

Difference between and in Java

What is the difference between List and List ? I used to use List, but it does not allow me to add elements to it list.add(e), whereas the List does.
Anand
  • 11,872
  • 10
  • 39
  • 51
896
votes
19 answers

Is List a subclass of List? Why are Java generics not implicitly polymorphic?

I'm a bit confused about how Java generics handle inheritance / polymorphism. Assume the following hierarchy - Animal (Parent) Dog - Cat (Children) So suppose I have a method doSomething(List animals). By all the rules of inheritance and…
froadie
  • 79,995
  • 75
  • 166
  • 235
895
votes
16 answers

What is PECS (Producer Extends Consumer Super)?

I came across PECS (short for Producer extends and Consumer super) while reading up on generics. Can someone explain to me how to use PECS to resolve confusion between extends and super?
peakit
  • 28,597
  • 27
  • 63
  • 80
883
votes
24 answers

How do I get a class instance of generic type T?

I have a generics class, Foo. In a method of Foo, I want to get the class instance of type T, but I just can't call T.class. What is the preferred way to get around it using T.class?
robinmag
  • 17,520
  • 19
  • 54
  • 55
832
votes
17 answers

How to get the type of T from a member of a generic class or method

Let's say I have a generic member in a class or method, like so: public class Foo { public List Bar { get; set; } public void Baz() { // get type of T } } When I instantiate the class, the T becomes…
Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
811
votes
16 answers

What is a raw type and why shouldn't we use it?

Questions: What are raw types in Java, and why do I often hear that they shouldn't be used in new code? What is the alternative if we can't use raw types, and how is it better?
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
744
votes
29 answers

How do I clone a generic list in C#?

I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do list.Clone(). Is there an easy way around this?
Fiona
  • 7,747
  • 4
  • 19
  • 8
696
votes
22 answers

How do I address unchecked cast warnings?

Eclipse is giving me a warning of the following form: Type safety: Unchecked cast from Object to HashMap This is from a call to an API that I have no control over which returns Object: HashMap
skiphoppy
  • 97,646
  • 72
  • 174
  • 218
694
votes
19 answers

How do I make the method return type generic?

Consider this example (typical in OOP books): I have an Animal class, where each Animal can have many friends. And subclasses like Dog, Duck, Mouse etc which add specific behavior like bark(), quack() etc. Here's the Animal class: public class…
Sathish
  • 20,660
  • 24
  • 63
  • 71
654
votes
13 answers

How can I return NULL from a generic method in C#?

I have a generic method with this (dummy) code (yes I'm aware IList has predicates, but my code is not using IList but some other collection, anyway this is irrelevant for the question...) static T FindThing(IList collection, int id) where T…
edosoft
  • 17,121
  • 25
  • 77
  • 111
650
votes
29 answers

Create instance of generic type in Java?

Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is no (due to type erasure), but I'd be interested if anyone can see something I'm missing: class SomeContainer { E…
David Citron
  • 43,219
  • 21
  • 62
  • 72
1
2 3
99 100