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
18
votes
5 answers

How to constrain generic type to must have a construtor that takes certain parameters?

I have a wrapper generic class that intended to be used with a set of types. Those types are generated by a utility and are all derived from a base class ClientBase. While ClientBase has only a default constructor, all generated types have default…
Hongwei Yan
  • 498
  • 1
  • 4
  • 11
18
votes
8 answers

When is it Appropriate to use Generics Versus Inheritance?

What are the situations and their associated benefits of using Generics over Inheritance and vice-versa, and how should they be best combined? Thanks for the answer guys. I'm going to try to state the motivation for this question as best I can: I…
Laz
  • 3,474
  • 9
  • 33
  • 46
18
votes
4 answers

"Set>" really?

I have been using a little generic method to create sets from vararg of elements, eg public Set createSet( T... elements ) { ... Recently, however, I came across a situation where the compiler did not do what I expected it to do. Of the…
Andrew Gilmartin
  • 1,776
  • 12
  • 12
18
votes
4 answers

Why there is a restriction for explicit casting a generic to a class type but there is no restriction for casting a generic to an interface type?

While reading Microsoft documentation, I stumbled on such an interesting code sample: interface ISomeInterface {...} class SomeClass {...} class MyClass { void SomeMethod(T t) { ISomeInterface obj1 = (ISomeInterface)t;//Compiles …
Yurii Hohan
  • 4,021
  • 4
  • 40
  • 54
18
votes
1 answer

Simplified Varargs Method Invocation in Java 7

In Java 7, you have the option to put a @SafeVarargs annotation to suppress the warning you get when compiling a method with a non-reifiable varargs parameter. Project Coin's proposal stipulates that the annotation should be used when the method…
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
18
votes
3 answers

How to create a Expression.Lambda when a type is not known until runtime?

This is best explained using code. I have a generic class that has a method that returns an integer. Here is a simple version for the purposes of explaining... public class Gen { public int DoSomething(T instance) { // Real code…
Phil Wright
  • 22,580
  • 14
  • 83
  • 137
18
votes
8 answers

In Java, how can I check if a collection contains an instance of a specific class?

For example (and this is very simplified), suppose I have a class for every card in a deck of cards... e.g. a KingOfSpaces class, a QueenOfSpades class, a JackOfDiamonds class, etc. All of which that extend Card. There might be multiple instances of…
Philihp Busby
  • 4,389
  • 4
  • 23
  • 19
18
votes
2 answers

Is there a type-safe way to pass an empty list as an argument in java?

The following code gives a compile error: public void method(List aList) {} public void passEmptyList() { method(Collections.emptyList()); } Is there a way to pass an empty list to method without Using an intermediate…
tb189
  • 1,942
  • 3
  • 22
  • 37
18
votes
5 answers

Generic data type conversion method

This question is in response to another question by opensas: building a generic initializer function in java From his question it became clear that he needs to convert from any data type T1 to another type T2. When I say "data type" here, I mean…
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
18
votes
3 answers

Writing a generic cast function Scala

I am trying to achieve to write a method that casts a value of Any to a specific type and returns option instead of throwing an exception like instanceOf. Scala does not behave like i have expected it: def cast[A](value: Any): Option[A] = { try …
18
votes
1 answer

How can I access a struct field with generics (type T has no field or method)?

I would like to make the following code compile. My understanding from reading the Type Parameters Proposal (Go Generics) is that this should work, but I must be missing something. package main import "fmt" func main() { s := Struct{A: "Hello…
Marc-François
  • 3,900
  • 3
  • 28
  • 47
18
votes
4 answers

How can I instantiate a non-nil pointer of type argument with generic Go?

Now that type parameters are available on golang/go:master, I decided to give it a try. It seems that I'm running into a limitation I could not find in the Type Parameters Proposal. (Or I must have missed it). I want to write a function which…
Tim
  • 1,585
  • 1
  • 18
  • 23
18
votes
1 answer

Strange lifetime error when iterating over a BTreeSet asynchronously

I want the async block in the following code to implement Send (Playground): use std::collections::BTreeSet; use std::future::ready; pub fn test(set: &BTreeSet) -> impl Send + '_ { async move { for _ in set { …
alephalpha
  • 560
  • 5
  • 13
18
votes
1 answer

The generic type already contains a definition

If I try to define the following Pair class in C#, I get a compiler error. public class Pair { public Pair(A a, B b) { this.A = a; this.B = b; } public A A { get; } public B B { get; } } The compiler…
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
18
votes
3 answers

JDK 11 Generics Issue when using Set.of

I am unable to understand the below issue for type safety when using JDK 11. Can anyone explain the reason for not getting a compilation error when I am directly passing the Set.of in the argument: public static void main(String[] args) { var…
Alok Dubey
  • 419
  • 4
  • 13