Questions tagged [generics]

Generics are a form of parametric polymorphism found in a range of languages, including .NET languages, Java, Swift, and Rust.

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 Generic Tutorials

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

.NET Generic Tutorials

  1. Introduction to Generics
  2. C# Generics

Rust Generic Tutorials

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

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
43896 questions
1388
votes
22 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 Now I want to sort…
Shyju
  • 197,032
  • 96
  • 389
  • 477
1276
votes
21 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
  • 36,657
  • 37
  • 96
  • 137
1155
votes
31 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
  • 22,689
  • 14
  • 37
  • 38
1141
votes
8 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
  • 40,925
  • 10
  • 77
  • 128
893
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
  • 10,392
  • 9
  • 36
  • 50
814
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
  • 71,770
  • 69
  • 154
  • 228
798
votes
15 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
  • 25,979
  • 25
  • 58
  • 77
762
votes
22 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
  • 15,600
  • 18
  • 51
  • 54
734
votes
16 answers

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

Let say I have a generic member in a class or method, so: public class Foo { public List Bar { get; set; } public void Baz() { // get type of T } } When I instantiate the class, the T becomes MyTypeObject1, so the…
Patrick Desjardins
  • 125,683
  • 80
  • 286
  • 335
719
votes
15 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
  • 348,637
  • 121
  • 546
  • 611
657
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
  • 6,897
  • 4
  • 17
  • 8
643
votes
23 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
  • 83,104
  • 64
  • 169
  • 214
627
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
  • 19,050
  • 22
  • 57
  • 69
604
votes
28 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
  • 41,009
  • 18
  • 60
  • 71
586
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
  • 16,270
  • 24
  • 75
  • 108
1
2 3
99 100