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
276
votes
14 answers

convert a list of objects from one type to another using lambda expression

I have a foreach loop reading a list of objects of one type and producing a list of objects of a different type. I was told that a lambda expression can achieve the same result. var origList = List(); // assume populated var targetList =…
Stratton
  • 3,493
  • 3
  • 19
  • 9
275
votes
11 answers

Generic type conversion FROM string

I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add typed properties, so that the "value" returned is always of the type that I…
Rob Cooper
  • 28,567
  • 26
  • 103
  • 142
273
votes
14 answers

What is the best way to clone/deep copy a .NET generic Dictionary?

I've got a generic dictionary Dictionary that I would like to essentially make a Clone() of ..any suggestions.
mikeymo
  • 3,145
  • 3
  • 23
  • 16
273
votes
5 answers

Scala: Abstract types vs generics

I was reading A Tour of Scala: Abstract Types. When is it better to use abstract types? For example, abstract class Buffer { type T val element: T } rather that generics, for example, abstract class Buffer[T] { val element: T }
thatismatt
  • 9,832
  • 10
  • 42
  • 54
268
votes
6 answers

What does the question mark in Java generics' type parameter mean?

This is a small snippet of code taken from some of the examples that accompany the Stanford Parser. I've been developing in Java for about 4 years, but have never had a very strong understanding of what this style of code is supposed to…
sholsapp
  • 15,542
  • 10
  • 50
  • 67
263
votes
7 answers

vs in Generics

What is the difference between and ? For example: public interface IExample { ... } vs. public interface IExample { ... }
Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
262
votes
9 answers

Java: how do I get a class literal from a generic type?

Typically, I've seen people use the class literal like this: Class cls = Foo.class; But what if the type is generic, e.g. List? This works fine, but has a warning since List should be parameterized: Class cls = List.class So why not add…
Tom
  • 18,685
  • 15
  • 71
  • 81
253
votes
2 answers

Correct way to check if a type is Nullable

In order to check if a Type ( propertyType ) is nullable, I'm using: bool isNullable = "Nullable`1".Equals(propertyType.Name) Is there some way that avoid using magic strings ?
Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
251
votes
15 answers

Performance of Arrays vs. Lists

Say you need to have a list/array of integers which you need iterate frequently, and I mean extremely often. The reasons may vary, but say it's in the heart of the inner most loop of a high volume processing. In general, one would opt for using…
Boaz
  • 25,331
  • 21
  • 69
  • 77
250
votes
8 answers

Mockito.any() pass Interface with Generics

is it possible to pass the type of an interface with generics? The interface: public interface AsyncCallback In my test method: Mockito.any(AsyncCallback.class) Putting behind or for .class didnt work.
lrxw
  • 3,576
  • 7
  • 32
  • 46
248
votes
8 answers

How to reference generic classes and methods in xml documentation

When writing xml documentation you can use something, which works of course. But how do you reference a class or a method with generic types? public class FancyClass { public string FancyMethod(T value) { return…
Svish
  • 152,914
  • 173
  • 462
  • 620
247
votes
7 answers

When do Java generics require instead of and is there any downside of switching?

Given the following example (using JUnit with Hamcrest matchers): Map> expected = null; Map> result = null; assertThat(result, is(expected)); This does not compile with the JUnit…
Yishai
  • 90,445
  • 31
  • 189
  • 263
239
votes
10 answers

Jackson - Deserialize using generic class

I have a json string, which I should deSerialize to the following class class Data { int found; Class hits } How do I do it? This is the usual way mapper.readValue(jsonString, Data.class); But how do I mention what T stands for?
gnjago
  • 3,391
  • 5
  • 19
  • 17
225
votes
6 answers

How to make a Java Generic method static?

The following is a snippet on how to make a java generic class to append a single item to an array. How can I make appendToArray a static method. Adding static to the method signature results in compile errors. public class ArrayUtils { …
Chris Johnson
  • 2,631
  • 2
  • 18
  • 17
222
votes
3 answers

Type must be a reference Type Error When Calling Generic Method

I get a compile error The type must be a reference type in order to use it as parameter 'T' in the generic type or method on the 'Derived' class below. How to resolve this? namespace Example { public class ViewContext { …
ChrisS
  • 2,595
  • 3
  • 18
  • 19