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
19
votes
1 answer

C# generics: what's the point of the "X where T: X" generic type constraint?

Reading a book: NHibernate 3: Beginners guide I found a fragment that made me curious: Time for action – Creating a base entity (...) Add a new class to the folder Domain of the project and call it Entity. Make the class abstract and generic in T.…
Paweł Bulwan
  • 8,467
  • 5
  • 39
  • 50
19
votes
3 answers

ICollection to string[]

I have a object of type ICollection. What is the best way to convert to string[]. How can this be done in .NET 2? How can this be done cleaner in later version of C#, perhaps using LINQ in C# 3?
leora
  • 188,729
  • 360
  • 878
  • 1,366
19
votes
5 answers

varargs heap pollution : what's the big deal?

I was reading about varargs heap pollution and I don't really get how varargs or non-reifiable types would be responsible for problems that do not already exist without genericity. Indeed, I can very easily replace public static void…
Dici
  • 25,226
  • 7
  • 41
  • 82
19
votes
2 answers

Swift: overriding typealias inside subclass

So I was thinking about a custom pattern in my project, but I can't get it to work. The main idea is to change the typealias on every subclass to get access to the subclass specific interface. protocol InstanceInterface: class { typealias…
DevAndArtist
  • 4,971
  • 1
  • 23
  • 48
19
votes
4 answers

Are EventArg classes needed now that we have generics

With generics, is there ever a reason to create specific derived EventArg classes It seems like now you can simply use them on the fly with a generic implementation. Should i go thorugh all of my examples and remove my eventArg classes…
leora
  • 188,729
  • 360
  • 878
  • 1,366
19
votes
4 answers

Why doesn't Java allow for the creation of generic arrays?

There are plenty of questions on stackoverflow from people who have attempted to create an array of generics like so: ArrayList[] poo = new ArrayList[5]; And the answer of course is that the Java specification doesn't allow you to declare…
dreadwail
  • 15,098
  • 21
  • 65
  • 96
19
votes
1 answer

Ambiguous method in Java 8, why?

public static void main(String... args){ then(bar()); // Compilation Error } public static E bar() { return null; } public static void then(Throwable actual) { } public static void then(CharSequence actual) {…
MariuszS
  • 30,646
  • 12
  • 114
  • 155
19
votes
5 answers

java warning: Varargs method could cause heap pollution from non-reifiable varargs parameter

I am using IntelliJ IDEA with javac on JDK 1.8. I have the following code: class Test { @SafeVarargs final void varargsMethod( Collection... varargs ) { arrayMethod( varargs ); } void…
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
19
votes
1 answer

Can I specify that a generic is a value type?

I know that we can essentially specify that our generics be any reference type by using AnyObject: class Foo { // ... } But is there a way to specify that our generics should only be value types, and not allow reference types?
nhgrif
  • 61,578
  • 25
  • 134
  • 173
19
votes
2 answers

Calling a Generic Method using Lambda Expressions (and a Type only known at runtime)

You can use Lambda Expression Objects to represent a lambda as an expression. How do you create a Lambda Expression Object representing a generic method call, if you only know the type -that you use for the generic method signature- at runtime? For…
SDReyes
  • 9,798
  • 16
  • 53
  • 92
19
votes
2 answers

Optional arguments in a generic Func<>

I have the following method in an assembly: public string dostuff(string foo, object bar = null) { /* ... */ } I use it as a callback, so a reference to it is passed to another assembly as such: Func dostuff Now in the…
h bob
  • 3,610
  • 3
  • 35
  • 51
19
votes
3 answers

Swift generic type conforming to two protocols

I have a generic method in one of my classes where I want to have a generic type conforming to UIViewController and UIPickerViewDelegate. How can I do that? I thought of doing this: func foo
borchero
  • 5,562
  • 8
  • 46
  • 72
19
votes
2 answers

How exactly do Generics work?

While looking up (testing) information for another question, I came across something and had completely no clue why it was happening. Now, I know that there is no practical reason to do this, and that this is absolutely horrific code, but why is it…
WiErD0
  • 467
  • 4
  • 16
19
votes
4 answers

Generics List and List not behaving as expected

Why is the println printing "tom" and not showing any runtime exception after casting to List, while it is not able to print the value 1 after casting to List? import java.util.Arrays; import java.util.List; public class Main { …
Aman
  • 213
  • 1
  • 7
19
votes
3 answers

IEnumerable> to IEnumerable using LINQ

How to split an IEnumerable of IEnumerables to one flat IEnumerable using LINQ (or someway else)?
abatishchev
  • 98,240
  • 88
  • 296
  • 433