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

Shouldn't ILookup be (declared) covariant in TElement?

The definition System.Linq.ILookUp reads interface ILookup : IEnumerable>, IEnumerable { int Count { get; } IEnumerable this[TKey key] { get; } bool Contains(TKey…
bigge
  • 1,488
  • 15
  • 27
20
votes
2 answers

Why does VS warn me that typeof(T) is never the provided type in a generic method where the type parameter is restricted to implement T?

I hope the question is correct, so let's give you an example. Imagine the following generic method: public abstract class Base : IDisposable { public static IEnumerable GetList() where T : Base { // To ensure T inherits…
Carsten
  • 11,287
  • 7
  • 39
  • 62
20
votes
2 answers

What's the point of generic type in foreach?

I'm curious - what is the point of generic type U in declaration of Traversable's foreach method? def foreach[U](f: A => U): Unit Since return type of Function1 is covariant, why can't that be just: def foreach(f: A => Any): Unit ?
ghik
  • 10,706
  • 1
  • 37
  • 50
20
votes
9 answers

Generic method that accept only part of classes

Suppose I have following class structure: class Base {} class A extends Base {} class B extends Base {} class C extends Base {} I want to write method, that accepts instances of A and B but not instances of C. Can I achieve it in Java? I know this…
Michał Herman
  • 3,437
  • 6
  • 29
  • 43
20
votes
2 answers

Cannot provide arguments when creating an instance of generic type

I have an object that I want to have read only after it is created... namely because the properties in the constructor must be used in GetHashCode, and therefore can't change once created. I this is one of many classes that are readonly: public…
makerofthings7
  • 60,103
  • 53
  • 215
  • 448
20
votes
1 answer

Why does Nullable not match as a reference type for generic constraints

Possible Duplicate: Nullable type as a generic parameter possible? I came across a very weird thing with generic type constraints. I have a class like this: public SomeClass where T:class { } However, I've found I can't use nullable types as…
Earlz
  • 62,085
  • 98
  • 303
  • 499
20
votes
4 answers

can I get .class from generic type argument?

I have the following class: public abstract class MyClass { protected T createNewFromData(Reader reader){ GSON.fromJSON(reader,T.class); // T.class isn't allowed :( } } How do I pass a Class instance into…
Mike S
  • 4,092
  • 5
  • 35
  • 68
20
votes
2 answers

C# casting an inherited Generic interface

I'm having some trouble getting my head around casting an interface I've come up with. It's an MVP design for C# Windows Forms. I have an IView class which I implement on my form classes. There's also an IPresenter which I derive into various…
Stephen York
  • 1,247
  • 1
  • 13
  • 42
20
votes
5 answers

Is there a generic alternative to the ListDictionary class?

I was looking at some sample code and in it they used a ListDictionary object to store a small amount of data (around 5-10 objects or so, but this number could change over time). The only issue I have with using this class is that, unlike everything…
Brian Surowiec
  • 17,123
  • 8
  • 41
  • 64
20
votes
5 answers

C# generics compared to C++ templates

Possible Duplicate: What are the differences between Generics in C# and Java… and Templates in C++? What are the differences between C# generics compared to C++ templates? I understand that they do not solve exactly the same problem, so what are…
Bjarke Freund-Hansen
  • 28,728
  • 25
  • 92
  • 135
20
votes
6 answers

Implementing IList interface

I am new to generics. I want to implement my own collection by deriving it from IList interface. Can you please provide me some link to a class that implements IList interface or provide me a code that at least implements Add and Remove…
Ashish Ashu
  • 14,169
  • 37
  • 86
  • 117
20
votes
0 answers

How to overload a method with generic parameter in java?

Possible Duplicate: Java erasure with generic overloading (not overriding) How to overloading method with generic parameter in java? Say I have following class import java.util.List; public class C { public void foo(List a){ …
Jyotirup
  • 2,882
  • 9
  • 30
  • 38
20
votes
3 answers

Java Generics: non-static type variable T cannot be referenced from a static context

interface A { interface B { // Results in non-static type variable T cannot // be referenced from a static context T foo(); } } Is there anyway round this? Why is T seen as static when referenced from A.B?
auser
  • 6,307
  • 13
  • 41
  • 63
20
votes
3 answers

Is it possible in C# to overload a generic cast operator in the following way?

Just wondering if there is anyway to represent the following code in C# 3.5: public struct Foo { public Foo(T item) { this.Item = item; } public T Item { get; set; } public static explicit operator Foo ( Foo a ) …
LaserJesus
  • 8,230
  • 7
  • 47
  • 65
20
votes
16 answers

What's the best way of using a pair (triple, etc) of values as one value in C#?

That is, I'd like to have a tuple of values. The use case on my mind: Dictionary, object> or Dictionary, object> Are there built-in types like Pair or Triple? Or what's the best way of implementing…
Massimiliano
  • 16,770
  • 10
  • 69
  • 112