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
166
votes
13 answers

No generic implementation of OrderedDictionary?

There doesn't appear to be a generic implementation of OrderedDictionary (which is in the System.Collections.Specialized namespace) in .NET 3.5. Is there one that I'm missing? I've found implementations out there to provide the functionality, but…
AdaTheDev
  • 142,592
  • 28
  • 206
  • 200
165
votes
6 answers

What does (angle brackets) mean in Java?

I am currently studying Java and have recently been stumped by angle brackets(<>). What exactly do they mean? public class Pool{ public interface PoolFactory{ public T createObject(); } this.freeObjects = new…
Laughy
  • 1,949
  • 5
  • 20
  • 22
163
votes
8 answers

Java generics T vs Object

I was wondering what is the difference between the following two method declarations: public Object doSomething(Object obj) {....} public T doSomething(T t) {....} Is there something you can/would do with one but not the other? I could not…
Abidi
  • 7,846
  • 14
  • 43
  • 65
163
votes
5 answers

Inherit from a generic base class, apply a constraint, and implement an interface in C#

This is a syntax question. I have a generic class which is inheriting from a generic base class and is applying a constraint to one of the type parameters. I also want the derived class to implement an interface. For the life of me, I cannot seem to…
Dan Rigby
  • 17,133
  • 6
  • 43
  • 60
162
votes
16 answers

Converting a generic list to a CSV string

I have a list of integer values (List) and would like to generate a string of comma delimited values. That is all items in the list output to a single comma delimted list. My thoughts... 1. pass the list to a method. 2. Use stringbuilder to iterate…
DenaliHardtail
  • 27,362
  • 56
  • 154
  • 233
161
votes
6 answers

What is the difference between ? and Object in Java generics?

I'm using Eclipse to help me clean up some code to use Java generics properly. Most of the time it's doing an excellent job of inferring types, but there are some cases where the inferred type has to be as generic as possible: Object. But Eclipse…
skiphoppy
  • 97,646
  • 72
  • 174
  • 218
160
votes
5 answers

Nullable type issue with ?: Conditional Operator

Could someone explain why this works in C#.NET 2.0: Nullable foo; if (true) foo = null; else foo = new DateTime(0); ...but this doesn't: Nullable foo; foo = true ? null : new DateTime(0); The…
Nick Gotch
  • 9,167
  • 14
  • 70
  • 97
160
votes
9 answers

When to use generic methods and when to use wild-card?

I am reading about generic methods from OracleDocGenericMethod. I am pretty confused about the comparison when it says when to use wild-card and when to use generic methods. Quoting from the document. interface Collection { public boolean…
benz
  • 4,561
  • 7
  • 37
  • 68
159
votes
5 answers

Mockito: Stubbing Methods That Return Type With Bounded Wild-Cards

Consider this code: public class DummyClass { public List dummyMethod() { return new ArrayList(); } } public class DummyClassTest { public void testMockitoWithGenerics() { DummyClass dummyClass…
Shikhar Mishra
  • 1,965
  • 2
  • 13
  • 14
159
votes
8 answers

Is it possible to solve the "A generic array of T is created for a varargs parameter" compiler warning?

This is a simplified version of the code in question, one generic class uses another class with generic type parameters and needs to pass one of the generic types to a method with varargs parameters: class Assembler { void assemble(X…
matt b
  • 138,234
  • 66
  • 282
  • 345
158
votes
3 answers

Java Map equivalent in C#

I'm trying to hold a list of items in a collection with a key of my choice. In Java, I would simply use Map as follows: class Test { Map entities; public String getEntity(Integer code) { return this.entities.get(code); …
anonymous-pek
158
votes
6 answers

Protocol can only be used as a generic constraint because it has Self or associatedType requirements

I have a protocol RequestType and it has associatedType Model as below. public protocol RequestType: class { associatedtype Model var path: String { get set } } public extension RequestType { public func…
Rahul Katariya
  • 3,528
  • 3
  • 19
  • 24
156
votes
7 answers

What is the concept of erasure in generics in Java?

What is the concept of erasure in generics in Java?
Tushu
  • 1,866
  • 3
  • 14
  • 19
154
votes
5 answers

How to dynamically create generic C# object using reflection?

In C# I have the following object: public class Item { } public class Task { } public class TaskA : Task { } public class TaskB : Task { } I want to dynamically create TaskA or TaskB using C# reflection (Activator.CreateInstance).…
Jeff
  • 13,079
  • 23
  • 71
  • 102
153
votes
3 answers

Kotlin - Void vs. Unit vs. Nothing

Kotlin has three types that are very similar in nature: Void Unit Nothing It almost seems like they're making the JavaScript mistake: null undefined void(0) Assuming that they haven't fallen into the same mistake, what are they all for, and how…
Matthew Layton
  • 39,871
  • 52
  • 185
  • 313