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

What would be different in Java if Enum declaration didn't have the recursive part

Please see Java Enum definition and Why in java enum is declared as Enum> for general discussion. Here I would like to learn what exactly would be broken (not typesafe anymore, or requiring additional casts etc) if Enum class was…
atamur
  • 1,567
  • 1
  • 14
  • 25
20
votes
4 answers

Generic method inside non-generic class

I'm using .net framework 4.0 I want to create a generic method inside a non-generic class but it gives me compile time error Error :The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) …
Amit Bisht
  • 4,870
  • 14
  • 54
  • 83
20
votes
5 answers

Why do we have contains(Object o) instead of contains(E e)?

Is it to maintain backwards compatibility with older (un-genericized) versions of Collection? Or is there a more subtle detail that I am missing? I see this pattern repeated in remove also (remove(Object o)), but add is genericized as add(E e).
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
20
votes
3 answers

In Java, what can a wild card do that regular generics cannot do?

I am new to Java. In this document they give this as a use case for using wildcard: static void printCollection(Collection c) { Iterator i = c.iterator(); for (int k = 0; k < c.size(); k++) { System.out.println(i.next()); …
developer747
  • 15,419
  • 26
  • 93
  • 147
20
votes
3 answers

Java Generics - Method overriding

I have a pair of classes ClassA & ClassB as shown below. case 1: class ClassA{ void method(T t){} } class ClassB extends ClassA{ @Override void method(Integer i){} } case 2: class ClassA{ void…
user4710520
20
votes
2 answers

Why doesn't C# support variant generic classes?

Take this small LINQPad example: void Main() { Foo foo = new Foo(); Console.WriteLine(foo.Get()); } class Foo { public T Get() { return default(T); } } It fails to compile with this…
Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
20
votes
6 answers

Why is it impossible to declare extension methods in a generic static class?

I'd like to create a lot of extension methods for some generic class, e.g. for public class SimpleLinkedList where T:IComparable And I've started creating methods like this: public static class LinkedListExtensions { public static T[]…
Hun1Ahpu
  • 3,315
  • 3
  • 28
  • 34
20
votes
6 answers

Why can't I cast one instantiation of a generic type to another?

How can I implement a struct so that the following cast can be performed? var a = new StatusedValue(1, false); var b = (StatusedValue)a; My implementation should behave similarly to Nullable, which works fine. However, this code…
Vladimir Sachek
  • 1,126
  • 1
  • 7
  • 20
20
votes
2 answers

How can I define an anonymous generic Scala function?

Let's say I have this: val myAnon:(Option[String],String)=>String = (a:Option[String],defVal:String) => { a.getOrElse(defVal) } Don't mind what the function does. Is there anyway of making it generic, so I can have an Option[T]?
Geo
  • 93,257
  • 117
  • 344
  • 520
20
votes
4 answers

Instantiate an object of a generic type in Swift

I am implementing a class Foo in Swift, that is supposed to instantiate objects of a given subclass of SuperBar, e.g. Bar: SuperBar. I really like generics in Swift, so I tried implementing it this way: class Foo { func…
knl
  • 1,404
  • 1
  • 14
  • 21
20
votes
2 answers

Limit on amount of generic parameters in .NET?

Is there a limit on the amount of generic parameters you can have on a type in .NET? Either hard limit (like 32) or a soft limit (where it somehow effects performance to much, etc.) What I'm referring to is: class Foo { }
thr
  • 19,160
  • 23
  • 93
  • 130
20
votes
1 answer

Odd debugger behavior with Interface and Generics on 64bit OS when toggling 'Prefer 32-Bit

I have come across this odd behaviour: when my projects settings are set to Any CPU and Prefer 32-bit on a 64bit Windows 7 OS the .Net 4.5program below works as expected. If however I turn off Prefer 32-bit then when stepping through the program, I…
Stephen Bailey
  • 1,931
  • 13
  • 20
20
votes
2 answers

How to implement a builder class using Generics, not annotations?

I want to write a generic builder class which wraps around any java class and providing setter functions of a specific style. I am not sure if this could be called "dynamically generated functions". When I have a beanish Pojo class i.e. class Pojo…
towi
  • 21,587
  • 28
  • 106
  • 187
20
votes
3 answers

Builder design pattern with inheritance: is there a better way?

I'm creating a series of builders to clean up the syntax which creates domain classes for my mocks as part of improving our overall unit tests. My builders essentially populate a domain class (such as a Schedule) with some values determined by…
cfeduke
  • 23,100
  • 10
  • 61
  • 65
20
votes
6 answers

Java Generics Interface casting

I stumbled across a Java casting situation involving Generics and Interfaces that I do not understand. Please consider the following code where I create a List. And then get() an element and cast it to Interface2 without compiler error…
Quota
  • 573
  • 3
  • 11