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

C# lambda expressions as function arguments

I've been busy diving into lambda expressions recently, and there's some specific functionality that I've been meaning to learn but just couldn't seem to make heads or tails of. Suppose that I have the following logic in my code: List foo; //…
Richard Neil Ilagan
  • 14,627
  • 5
  • 48
  • 66
19
votes
5 answers

Switch based on generic argument type

In C# 7.1 the below is valid code: object o = new object(); switch (o) { case CustomerRequestBase c: //do something break; } However, I want to use the pattern switch statement in the following scenario: public T…
19
votes
5 answers

How do I get the value of an Enum, if I don't know the class at compile time?

I'm trying to do the following: Class cls = unknownClass; if(cls.isEnum()){ @SuppressWarnings("unchecked") Class> enumClass = (Class>) cls; Object val = Enum.valueOf(enumClass, "NAME1"); } But I…
cammil
  • 9,499
  • 15
  • 55
  • 89
19
votes
4 answers

How does this compile?

I'm writing a function that takes a list of keyExtractor functions to produce a Comparator (imagine we had an object with many many properties and wanted to be able to arbitrarily compare by a large number of properties in any order). import…
19
votes
5 answers

Typescript with React - use HOC on a generic component class

I have a generic React component, say like this one: class Foo extends React.Component, FooState> { constructor(props: FooProps) { super(props); render() { return

The result is…

Joald
  • 1,114
  • 10
  • 32
19
votes
6 answers

How to not throw a generically specified exception?

I created a "producer" interface (to be used with method references, respectively to be easily mocked for unit tests): @FunctionalInterface public interface Factory { public R newInstanceFor(T t) throws X; } which I…
GhostCat
  • 137,827
  • 25
  • 176
  • 248
19
votes
5 answers

How to pass a parameterized class as an argument

My goal is to develop a class that can output an object of a specified class. public class GetMe { public T get() { Object obj = generateObject(); return (T) obj; } } Now, I know this isn't possible due to erasure. So,…
Monkey Boson
  • 1,250
  • 4
  • 11
  • 21
19
votes
3 answers

How can I create a singleton IEnumerable?

Does C# offer some nice method to cast a single entity of type T to IEnumerable? The only way I can think of is something like: T entity = new T(); IEnumerable = new List { entity }.AsEnumerable(); And I guess there should be a better way.
Yippie-Ki-Yay
  • 22,026
  • 26
  • 90
  • 148
19
votes
4 answers

Method return type to fulfill multiple interfaces

Is it possible to specify a method which returns a object that implements two or multiple interfaces? Say we have the following interfaces: interface FooBar { [Foo] & [Bar] getFooBar(); } interface Foo { void doFoo(); } inteface Bar { …
z00bs
  • 7,518
  • 4
  • 34
  • 53
19
votes
2 answers

Is there a Many to Many Collection in Java using Generics (Domain Model, not Persistence Layer)?

I seem to be using the wrong search terms for this in Google... I have written a Generic Class for Many-To-Many Associations, but I'm guessing this has already been done. It is highly likely that it exists in an implementation much better than my…
Daniel Bower
  • 739
  • 1
  • 7
  • 27
19
votes
9 answers

What does "where" mean in a C# class declaration?

I tried to google this, but all I could find was documents on ordinary class declarations. public class DataContextWrapper : IDataContextWrapper where T : DataContext, new() { } I see that the class implements IDataContextWrapper, inherits from…
MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
19
votes
3 answers

java8 functional interface to handle the callback

I have a generic private method which does common tasks and is used by other methods. The generic method has if and else conditions to support other methods that are called. Example: private void myGenericMethod(String name, int age){ common…
zilcuanu
  • 3,451
  • 8
  • 52
  • 105
19
votes
2 answers

TypeScript: How to deal with generic types and the keyof operator

I try to write a generic function which assembles update data for database updates. Passed arguments: record to be updated property key a new array item Even though I restrict the key's type using keyof R, I cannot assign a new object with that…
ideaboxer
  • 3,863
  • 8
  • 43
  • 62
19
votes
2 answers

How is the empty interface different than a generic?

Maybe I'm not fully versed on the power of generics, but how is the empty interface, interface{}, different than a generic, especially if we have the ability to use reflection or type switches? People always mention that Go doesn't have generics,…
ollien
  • 4,418
  • 9
  • 35
  • 58
19
votes
1 answer

Incompatible types inferred type does not conform to equality constraint(s)

So I have a model Model. public class Model { .... } This has two subclasses: public class SubmodelA extend Model { .... } and public class SubmodelB extend Model { .... } These three are wrapped under Data class. public class ApiData
Manos
  • 1,471
  • 1
  • 28
  • 45