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
454
votes
20 answers

Passing a single item as IEnumerable

Is there a common way to pass a single item of type T to a method which expects an IEnumerable parameter? Language is C#, framework version 2.0. Currently I am using a helper method (it's .Net 2.0, so I have a whole bunch of casting/projecting…
vgru
  • 49,838
  • 16
  • 120
  • 201
450
votes
11 answers

What are the reasons why Map.get(Object key) is not (fully) generic

What are the reasons behind the decision to not have a fully generic get method in the interface of java.util.Map. To clarify the question, the signature of the method is V get(Object key) instead of V get(K key) and I'm wondering why (same…
WMR
  • 12,661
  • 5
  • 35
  • 30
435
votes
2 answers

Java Generics With a Class & an Interface - Together

I want to have a Class object, but I want to force whatever class it represents to extend class A and implement interface B. I can do: Class Or: Class but I can't do both. Is there a way to do this?
Alex Beardsley
  • 20,988
  • 15
  • 52
  • 67
432
votes
8 answers

Method has the same erasure as another method in type

Why is it not legal to have the following two methods in the same class? class Test{ void add(Set ii){} void add(Set ss){} } I get the compilation error Method add(Set) has the same erasure add(Set) as another method in…
Omry Yadan
  • 31,280
  • 18
  • 64
  • 87
397
votes
14 answers

Can't operator == be applied to generic types in C#?

According to the documentation of the == operator in MSDN, For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true…
Hosam Aly
  • 41,555
  • 36
  • 141
  • 182
388
votes
3 answers

How does the reified keyword in Kotlin work?

I'm trying to understand the purpose of the reified keyword. Apparently, it's allowing us to do reflection on generics. However, when I leave it out, it works just as fine. When does this make an actual difference?
hl3mukkel
  • 5,369
  • 3
  • 21
  • 21
385
votes
11 answers

What does "where T : class, new()" mean?

Can you please explain to me what where T : class, new() means in the following line of code? void Add(T item) where T : class, new();
Rawhi
  • 6,155
  • 8
  • 36
  • 57
383
votes
12 answers

Using Mockito to mock classes with generic parameters

Is there a clean method of mocking a class with generic parameters? Say I have to mock a class Foo which I need to pass into a method that expects a Foo. I can do the following easily enough: Foo mockFoo =…
Tim Clemons
  • 6,231
  • 4
  • 25
  • 23
366
votes
4 answers

Case insensitive access for generic dictionary

I have an application that use managed dlls. One of those dlls return a generic dictionary: Dictionary MyDictionary; The dictionary contains keys with upper and lower case. On another side I am getting a list of potential keys…
TocToc
  • 4,739
  • 4
  • 29
  • 34
363
votes
9 answers

Why is "extends T" allowed but not "implements T"?

Is there a special reason in Java for using always "extends" rather than "implements" for defining bounds of type parameters? For example: public interface C {} public class A{} is prohibited, but public class A{} is…
user120623
  • 3,631
  • 2
  • 17
  • 3
360
votes
13 answers

Nullable type as a generic parameter possible?

I want to do something like this : myYear = record.GetValueOrNull("myYear"), Notice the nullable type as the generic parameter. Since the GetValueOrNull function could return null my first attempt was this: public static T…
Tom Pester
  • 3,643
  • 2
  • 17
  • 5
351
votes
16 answers

Check if a class is derived from a generic class

I have a generic class in my project with derived classes. public class GenericClass : GenericInterface { } public class Test : GenericClass { } Is there any way to find out if a Type object is derived from…
bernhardrusch
  • 11,670
  • 12
  • 48
  • 59
345
votes
12 answers

What causes javac to issue the "uses unchecked or unsafe operations" warning

For example: javac Foo.java Note: Foo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
user23987
344
votes
14 answers

Null or default comparison of generic argument in C#

I have a generic method defined like this: public void MyMethod(T myArgument) The first thing I want to do is check if the value of myArgument is the default value for that type, something like this: if (myArgument == default(T)) But this…
Stefan Moser
  • 6,663
  • 9
  • 35
  • 48
341
votes
8 answers

IEnumerable and Recursion using yield return

I have an IEnumerable method that I'm using to find controls in a WebForms page. The method is recursive and I'm having some problems returning the type I want when the yield return is returnig the value of the recursive call. My code looks as…
Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162