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
222
votes
25 answers

Generic TryParse

I am trying to create a generic extension that uses 'TryParse' to check if a string is a given type: public static bool Is(this string input) { T notUsed; return T.TryParse(input, out notUsed); } this won't compile as it cannot resolve…
Piers Myers
  • 10,611
  • 6
  • 46
  • 61
221
votes
6 answers

Pass An Instantiated System.Type as a Type Parameter for a Generic Class

The title is kind of obscure. What I want to know is if this is possible: string typeName = ; Type myType = Type.GetType(typeName); MyGenericClass myGenericClass = new MyGenericClass(); Obviously,…
Robert C. Barth
  • 22,687
  • 6
  • 45
  • 52
218
votes
12 answers

Static method in a generic class?

In Java, I'd like to have something as: class Clazz { static void doIt(T object) { // ... } } But I get Cannot make a static reference to the non-static type T I don't understand generics beyond the basic uses and thus can't make much…
André Chalella
  • 13,788
  • 10
  • 54
  • 62
214
votes
8 answers

C# Create New T()

You can see what I'm trying (but failing) to do with the following code: protected T GetObject() { return new T(); } Any help would be greatly appreciated. EDIT: The context was as follows. I was playing around with a custom controller class…
Hanshan
  • 3,656
  • 5
  • 29
  • 36
213
votes
7 answers

How do I make the return type of a method generic?

Is there a way to make this method generic so I can return a string, bool, int, or double? Right now, it's returning a string, but if it's able find "true" or "false" as the configuration value, I'd like to return a bool for example. public…
JustBeingHelpful
  • 18,332
  • 38
  • 160
  • 245
213
votes
13 answers

How can I convert int[] to Integer[] in Java?

I have a large dataset of length 4 int[] and I want to count the number of times that each particular combination of 4 integers occurs. This is very similar to counting word frequencies in a document. I want to create a Map that maps…
John
213
votes
12 answers

Create a new object from type parameter in generic class

I'm trying to create a new object of a type parameter in my generic class. In my class View, I have 2 lists of objects of generic type passed as type parameters, but when I try to make new TGridView(), TypeScript says: Could not find symbol…
Javier Ros
  • 3,511
  • 2
  • 21
  • 41
208
votes
13 answers

foreach vs someList.ForEach(){}

There are apparently many ways to iterate over a collection. Curious if there are any differences, or why you'd use one way over the other. First type: List someList = foreach(string s in someList) {
Bryce Fischer
  • 5,336
  • 9
  • 30
  • 36
208
votes
9 answers

Is there a generic constructor with parameter constraint in C#?

In C# you can put a constraint on a generic method like: public class A { public static void Method (T a) where T : new() { //...do something... } } Where you specify that T should have a constructor that requires no…
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
205
votes
10 answers

Difference between List, List, List, List, and List
What are the differences between List, List, List, List, and List? 1. List List: is a raw type, therefore not typesafe. It will only generate a runtime error when the casting is bad. We want a compile time error when the cast is…
Thang Pham
  • 38,125
  • 75
  • 201
  • 285
205
votes
29 answers

How do you convert a DataTable into a generic list?

Currently, I'm using: DataTable dt = CreateDataTableInSomeWay(); List list = new List(); foreach (DataRow dr in dt.Rows) { list.Add(dr); } Is there a better/magic way?
Iain Holder
  • 14,172
  • 10
  • 66
  • 86
205
votes
11 answers

How can I use interface as a C# generic type constraint?

Is there a way to get the following function declaration? public bool Foo() where T : interface; ie. where T is an interface type (similar to where T : class, and struct). Currently I've settled for: public bool Foo() where T : IBase; Where…
Matthew Scharley
  • 127,823
  • 52
  • 194
  • 222
203
votes
13 answers

What are the differences between Generics in C# and Java... and Templates in C++?

I mostly use Java and generics are relatively new. I keep reading that Java made the wrong decision or that .NET has better implementations etc. etc. So, what are the main differences between C++, C#, Java in generics? Pros/cons of each?
pek
  • 17,847
  • 28
  • 86
  • 99
203
votes
13 answers

How do I combine two lists in Dart?

I was wondering if there was an easy way to concatenate two lists in dart to create a brand new list object. I couldn't find anything and something like this: My list: list1 = [1, 2, 3] list2 = [4, 5, 6] I tried: var newList = list1 + list2; I…
Alex
  • 2,033
  • 2
  • 11
  • 7
203
votes
4 answers

Mockito: List Matchers with generics

Mockito offers: when(mock.process(Matchers.any(List.class))); How to avoid warning if process takes a List instead?
Philippe Blayo
  • 10,610
  • 14
  • 48
  • 65