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

ASP.NET MVC Model Binder for Generic Type

Is it possible to create a model binder for a generic type? For example, if I have a type public class MyType Is there any way to create a custom model binder that will work for any type of MyType? Thanks, Nathan
Nathan Roe
  • 844
  • 1
  • 8
  • 22
19
votes
2 answers

Implementing the same interface at different generic instantiations

In C#, I can implement a generic interface twice on one class, using two different type-parameters: interface IFoo { void Foo(T x); } class Bar : IFoo, IFoo { public void Foo(int x) { } public void Foo(float y) { } } I would…
Gabriel
  • 1,443
  • 15
  • 24
19
votes
8 answers

Parse string to enum type

I have an enum type like this as an example: public Enum MyEnum { enum1, enum2, enum3 }; I'll read a string from config file. What I need is to parse the string to MyEnum type or null or not defined. Not sure if the following code will work…
David.Chu.ca
  • 37,408
  • 63
  • 148
  • 190
19
votes
3 answers

Java name clash, have the same erasure, neither hides the other

I am getting this name clash error and i don't know how should i solve the problem. I have two classes and i am using overloaded method "createSensors". To simplify here is the code that generates the problem: public abstract class ClassA { …
user506246
  • 301
  • 1
  • 4
  • 15
19
votes
2 answers

Generics hell: hamcrest matcher as a method parameter

So, let's have a list of strings and a function that takes a Hamcrest matcher and returns a result of the matches() method of the provided matcher: public boolean matchIt(final Matcher> matcher) { final List lst =…
Jan Dudek
  • 271
  • 3
  • 7
19
votes
5 answers

Convert from IList to non-generic IList

I am implementing IListSource that requires a method GetList() with the following signature: IList GetList() I am using .NET framework 2 and I'm wanting to return an object that implements IList as follows: public System.Collections.IList…
BruceHill
  • 6,954
  • 8
  • 62
  • 114
19
votes
3 answers

Visual Studio 2012 - Self Referencing Generics Parsing Errors

I'm having a bit of trouble here, in our company we have a self rolled DA layer which uses self referencing generics. In Visual Studio 2010, the IDE was perfectly happy with this, however 2012 seems to be having difficulty, even though when we…
Marlon
  • 2,129
  • 3
  • 21
  • 40
19
votes
2 answers

Getting Allen Bauer's TMulticastEvent working

I've been mucking around with Allen Bauer's code for a generic multicast event dispatcher (see his blog posts about it here). He gives just enough code to make me want to use it, and unfortunately he hasn't posted the full source. I had a bash at…
Nat
  • 5,414
  • 26
  • 38
19
votes
3 answers

c# generics error: The constraints for type parameter 'T' of method ...?

Getting the following error: Error 1 The constraints for type parameter 'T' of method 'genericstuff.Models.MyClass.GetCount(string)' must match the constraints for type parameter 'T' of interface method…
user603007
  • 11,416
  • 39
  • 104
  • 168
18
votes
4 answers

How to Convert a String to a Nullable Type Which is Determined at Runtime?

I have the below code and I'd need to convert a string to a type which is also specified from String: Type t = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); …
The Light
  • 26,341
  • 62
  • 176
  • 258
18
votes
2 answers

Where are generic types stored in java class files?

I am well aware that generic types are erased from Java code when it is compiled. What information (attributes?) do 1.5+ JVMs use to implement getGenericType , etc. ?
Joe
  • 427
  • 3
  • 10
18
votes
10 answers

How to cast generic List types in java?

Well, I have a class Customer (no base class). I need to cast from LinkedList to List. Is there any clean way to do this? Just so you know, I need to cast it to List. No other type will do. (I'm developing a test fixture using Slim and…
jrharshath
  • 25,975
  • 33
  • 97
  • 127
18
votes
3 answers

Java bounded wildcard in return type

I've read in various places including here that having a bounded wildcard in a method return type is a bad idea. However, I can't find a way to avoid it with my class. Am I missing something? The situation looks something like this: class…
thehouse
  • 7,957
  • 7
  • 33
  • 32
18
votes
11 answers

Java Generics and numbers

In an attempt to see if I can clean up some of my math code, mostly matrix stuff, I am trying to use some Java Generics. I have the following method: private T[][] zeroMatrix(int row, int col) { T[][] retVal = (T[][])new Object[row][col]; …
Scott Lemke
  • 373
  • 4
  • 6
18
votes
2 answers

Generics Hell: Can I construct a TypeLiteral> using generics?

The only way I was able to get the below generic method to work was to pass the seemingly redundant TypeLiteral> parameter. I believe it should be possible to construct this parameter programmatically given the other parameter, but can't…
Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246