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
21
votes
4 answers

Java Object return type vs. Generic Methods

I saw several questions about generic return type, but none answers my question. If there is no bound for any of the arguments, such as the following method in JayWay : public static T read(String json, String jsonPath, Filter... filters) { …
Nati
  • 1,034
  • 5
  • 19
  • 46
21
votes
2 answers

Why generic interfaces are not co/contravariant by default?

For example IEnumerable interface: public interface IEnumerable : IEnumerable { IEnumerator GetEnumerator(); } In this interface the generic type is used only as a return type of interface method and not used as a type of method…
Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121
21
votes
8 answers

How to implement factory pattern with generics in Java?

I have a generic interface Handler public interface Handler { void handle(T obj); } I can have n implementations of this interface. Let's say I have following 2 implementations for now. One which handles String objects and another handles…
user1522820
  • 1,584
  • 5
  • 18
  • 31
21
votes
5 answers

Why is it possible to get back an object of "incorrect-type" from the parametrized List in Java?

Here's a code snippet: import java.util.*; class Test { public static void main(String[] args) { List list = new ArrayList<>(); addToList(list); Integer i = list.get(0); //#1 fails at run-time String…
fromSPb
  • 313
  • 2
  • 9
21
votes
1 answer

Initialize generic object from a System.Type

I need to create a generic type, but I do not know the type at compile time. I would like to do this: Type t = typeof(whatever); var list = new List this won't compile, because t is not a valid type. But it does know all about a valid type. Is…
captncraig
  • 22,118
  • 17
  • 108
  • 151
21
votes
1 answer

Generics, Type Parameters and Wildcards

I am trying to understand java generics and they seem extremely difficult to understand. For example, this is fine... public class Main { public static void main(String[] args) { List list = null; method(list); } …
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
21
votes
2 answers

Why does ((IList)array).ReadOnly = True but ((IList)array).ReadOnly = False?

I know that in .NET all arrays derive from System.Array and that the System.Array class implements IList, ICollection and IEnumerable. Actual array types also implement IList, ICollection and IEnumerable. This means that if you have, for…
J Smith
  • 2,375
  • 3
  • 18
  • 36
21
votes
5 answers

A reusable pattern to convert event into task

I'd like to have a generic reusable piece of code for wrapping EAP pattern as task, something similar to what Task.Factory.FromAsync does for BeginXXX/EndXXX APM pattern. E.g.: private async void Form1_Load(object sender, EventArgs e) { await…
noseratio
  • 59,932
  • 34
  • 208
  • 486
21
votes
5 answers

How do arrays "remember" their types in Java?

Consider the following code: class AA { } class BB extends AA { } public class Testing { public static void main(String[] args) { BB[] arr = new BB[10]; AA[] arr2 = arr; BB b = new BB(); AA a = new AA(); …
brain storm
  • 30,124
  • 69
  • 225
  • 393
21
votes
5 answers

How can elements be added to a wildcard generic collection?

Why do I get compiler errors with this Java code? 1 public List getFoos() 2 { 3 List foos = new ArrayList(); 4 foos.add(new SubFoo()); 5 return foos; 6 } Where 'SubFoo' is a concrete class…
David Koelle
  • 20,726
  • 23
  • 93
  • 130
21
votes
8 answers

How to make a Java interface that extends Iterable with two different generic types?

Ideally, it would look like this (the context doesn't matter): public interface myInterface extends Iterable, Iterable { ... } But this is not allowed in Java. How can I achieve this behaviour?
user2460978
  • 735
  • 6
  • 19
21
votes
4 answers

Check which type of object List contains

List contains the object type, but I need to check if that object is of type A or B: A a = new A(); B b = new B(); List aL = new ArrayList(); List bL = new ArrayList(); How can I check whether List contains A objects or B…
Shivababa
  • 339
  • 1
  • 3
  • 8
21
votes
2 answers

How to conditionally invoke a generic method with constraints?

Suppose I have an unconstrained generic method that works on all types supporting equality. It performs pairwise equality checks and so works in O(n2): public static int CountDuplicates(IList list) { /* ... */ } I also have a…
Piotr Shatalin
  • 443
  • 3
  • 8
21
votes
8 answers

In C# how can i check if T is of type IInterface and cast to that if my object supports that interface?

In C#, I have a function that passes in T using generics and I want to run a check to see if T is an object that implements a interface and if so call one of the methods on that interface. I don't want to have T constraints to only be of that Type. …
leora
  • 188,729
  • 360
  • 878
  • 1,366
21
votes
3 answers

There is no implicit reference conversion from 'System.Collections.Generic.List' to 'T'

class Class1 { public virtual void Update(T entity) { Update(new List() { entity }); //It's failed } public virtual void Update(IEnumerable entities) { } public virtual void Update(TSub entity)…
Jailu Lee
  • 611
  • 1
  • 8
  • 13