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
19
votes
3 answers

Differentiating between ">>" and ">" when parsing generic types

My first Stack Overflow question. I have always been curious about this. Say you are parsing the following line of code: List> list = new List>(); When parsing, a naive tokenizer will assume that the two right angle…
Josh Wyant
  • 1,177
  • 1
  • 8
  • 13
19
votes
2 answers

Reflection - check all nullable properties have values

I have to loop through all the properties in a few classes and check any nullable properties to see if they have a value. How do I cast the value returned from propertyInfo.GetValue() to a generic nullable type so that I can check the HasValue…
Paddy
  • 33,309
  • 15
  • 79
  • 114
19
votes
6 answers

Unbounded wildcards in Java

Is there ever a difference between an unbounded wildcard e.g. and a bounded wildcard whose bound is Object, e.g. ? I recall reading somewhere that there was a difference in the early drafts of generics, but cannot find that…
notnoop
  • 58,763
  • 21
  • 123
  • 144
19
votes
2 answers

java generics: getting class of a class with generic parameters

I am curious how to make this work Class> food = Map.class; That obviously doesn't work. I would want something like this Class> food = Map.class; but this seems like not a valid java…
Surya
  • 4,922
  • 8
  • 41
  • 54
19
votes
5 answers

and for List

Having the following simple class structure: class A { } class B extends A { } class C extends B { } I'm creating an ArrayList to keep objects of the earlier created classes: List list1 = new ArrayList(); List list2 =…
qbaquak
  • 193
  • 1
  • 4
19
votes
2 answers

Using generic case classes in Scala

I wonder whether using generics for Scala case classes can save some boilerplate code. Let's save I have the following class hieararchy to emulate a "variant" type that boxes a set of types and allows unboxing them using pattern matching: sealed…
Alexey Alexandrov
  • 2,951
  • 1
  • 24
  • 24
19
votes
4 answers

Is it possible to parcel a generic class?

I'm trying to create public class MyClass implements Parcelable. I'm having trouble implementing Parcelable. Is it possible to create a generic class that implements Parcelable? (Note that T is bounded so that it also must…
Andre Gregori
  • 1,150
  • 1
  • 10
  • 17
19
votes
1 answer

Scala: who can explain this?

Consider the following Scala code: case class Data[T](value: Option[T]) { def get: T = try { doGet } catch { case e: Exception => throw new IllegalArgumentException } def doGet: T = value match { case Some(v) => v case None…
Hugo Zwaal
  • 193
  • 3
19
votes
1 answer

Create Generic Expression from string property name

I have a variable called sortColumn, which contains the text of a column that I want to sort a query result by. I also have a generic repository which takes as a parameter an Expression that contains the field I want to sort by. I can't seem to…
Paul Cavacas
  • 4,194
  • 5
  • 31
  • 60
19
votes
6 answers

Java generics and typecasting

I have a badly created container object that holds together values of different java types(String, Boolean etc ..) public class BadlyCreatedClass { public Object get(String property) { ...; } }; And we extract values from it in this…
jack_carver
  • 1,510
  • 2
  • 13
  • 28
19
votes
2 answers

JAXB Bindings File Sets @XmlElement type to String instead of XMLGregorianCalendar

I'm trying to create an XmlAdapter that takes in an XMLGregorianCalendar and outputs an XMLGregorianCalendar. The purpose is simlply to remove timezone data from the element when unmarshalling data. It looks like this: public class…
summer
  • 711
  • 1
  • 5
  • 15
19
votes
3 answers

How to call a generic extension method with reflection?

I wrote the extension method GenericExtension. Now I want to call the extension method Extension. But the value of methodInfo is always null. public static class MyClass { public static void GenericExtension(this Form a, string b) where T :…
David
  • 4,027
  • 10
  • 50
  • 102
19
votes
4 answers

Delegate for any method type - C#

I want to have a class that will execute any external method, like this: class CrazyClass { //other stuff public AnyReturnType Execute(AnyKindOfMethod Method, object[] ParametersForMethod) { //more stuff return…
Daniel Möller
  • 84,878
  • 18
  • 192
  • 214
19
votes
4 answers

Lazy class cast in Java?

Can someone please enlighten me as to why I don't get a ClassCastException in this snippet? I'm strictly interested into why it isn't working as I was expecting. I don't care at this point whether this is bad design or not. public class Test { …
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
19
votes
6 answers

Iterating over a map entryset

I need to iterate over the entry set of a map from which I do not know its parameterized types. When iterating over such entryset, why this does not compile ? public void myMethod(Map anyMap) { for(Entry entry : anyMap.entrySet()) { ... …
Sergio
  • 8,532
  • 11
  • 52
  • 94