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

Select a Dictionary with LINQ

I have used the "select" keyword and extension method to return an IEnumerable with LINQ, but I have a need to return a generic Dictionary and can't figure it out. The example I learned this from used something in a form similar to the…
Rich
  • 36,270
  • 31
  • 115
  • 154
202
votes
8 answers

Why are arrays covariant but generics are invariant?

From Effective Java by Joshua Bloch, Arrays differ from generic type in two important ways. First arrays are covariant. Generics are invariant. Covariant simply means if X is subtype of Y then X[] will also be sub type of Y[]. Arrays are covariant…
eagertoLearn
  • 9,772
  • 23
  • 80
  • 122
199
votes
4 answers

Difference between "*" and "Any" in Kotlin generics

I am not sure I fully understand the difference between SomeGeneric<*> and SomeGeneric. I think * represents anything (wild card) and Any represents the object which ALL objects inherit from. So it seems they should be the same, but are they?
Wheel Builder
  • 3,515
  • 5
  • 20
  • 32
199
votes
4 answers

Func with out parameter

Can I pass a method with an out parameter as a Func? public IList FindForBar(string bar, out int count) { } // somewhere else public IList Find(Func> listFunction) { } Func needs a type so out won't compile there, and…
blu
  • 12,905
  • 20
  • 70
  • 106
198
votes
10 answers

Generic List - moving an item within the list

So I have a generic list, and an oldIndex and a newIndex value. I want to move the item at oldIndex, to newIndex...as simply as possible. Any suggestions? Note The item should be end up between the items at (newIndex - 1) and newIndex before it was…
Richard Ev
  • 52,939
  • 59
  • 191
  • 278
191
votes
9 answers

What is out keyword in kotlin

I am not able to understand and I couldn't find the meaning of out keyword in kotlin. You can check example here: List If any one can explain the meaning of this. It would be really appreciated.
Akshay Sood
  • 6,366
  • 10
  • 36
  • 59
191
votes
6 answers

Value of type 'T' cannot be converted to

This is likely a a novice question, but google surprisingly did not provide an answer. I have this rather artificial method T HowToCast(T t) { if (typeof(T) == typeof(string)) { T newT1 = "some text"; T newT2 = (string)t; …
Alex
  • 2,301
  • 2
  • 16
  • 15
188
votes
3 answers

C# - Multiple generic types in one list

This is probably not possible, but I have this class: public class Metadata where DataType : struct { private DataType mDataType; } There's more to it, but let's keep it simple. The generic type (DataType) is limited to value types…
Carl
  • 2,415
  • 3
  • 17
  • 7
187
votes
5 answers

Why can't the C# constructor infer type?

Why is type inference not supported for constructors the way it is for generic methods? public class MyType { private readonly T field; public MyType(T value) { field = value; } } var obj = new MyType(42); // why can't type inference work…
theburningmonk
  • 15,701
  • 14
  • 61
  • 104
186
votes
10 answers

What is a difference between and ?

What is the difference between and ? For instance when you take a look at class java.util.concurrent.LinkedBlockingQueue there is the following signature for the constructor: public LinkedBlockingQueue(Collection
Tomasz Błachowicz
  • 5,731
  • 9
  • 41
  • 47
183
votes
7 answers

How can I add to List data structures?

I have a List which is declared like this : List foo3 = new ArrayList(); I tried to add 3 to foo3. However I get an error message like this: The method add(capture#1-of ? extends Number) in the type List
unj2
  • 52,135
  • 87
  • 247
  • 375
182
votes
6 answers

Why doesn't Java allow generic subclasses of Throwable?

According to the Java Language Sepecification, 3rd edition: It is a compile-time error if a generic class is a direct or indirect subclass of Throwable. I wish to understand why this decision has been made. What's wrong with generic…
Hosam Aly
  • 41,555
  • 36
  • 141
  • 182
180
votes
6 answers

Testing if object is of generic type in C#

I would like to perform a test if an object is of a generic type. I've tried the following without success: public bool Test() { List list = new List(); return list.GetType() == typeof(List<>); } What am I doing wrong and how do…
Richbits
  • 7,344
  • 8
  • 33
  • 38
180
votes
7 answers

How can I make a generic type optional?

I have the following logging method: private logData(operation: string, responseData: T, requestData?: S) { this.logger.log(operation + ' ' + this.url); if (requestData) { this.logger.log('SENT'); …
Marius
  • 3,253
  • 5
  • 25
  • 29
179
votes
6 answers

Kotlin: How to work with List casts: Unchecked Cast: kotlin.collections.List to kotlin.colletions.List

I want to write a function that returns every item in a List that is not the first or the last item (a via point). The function gets a generic List<*> as input. A result should only be returned if the elements of the list are of the type…
Lukas Lechner
  • 7,881
  • 7
  • 40
  • 53