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

List or List
I have a method whose argument should be "a List of anything". The method will not modify the contents of the List. Is it more correct to define this method as void foo(List list) { } or void foo(List list) { } and what exactly is the…
Dónal
  • 185,044
  • 174
  • 569
  • 824
20
votes
3 answers

Rust macro accepting type with generic parameters

I have a macro that implements a trait, impl_Trait!(). Right now, it works for types without generic parameters, but I'm not sure how to add the type parameters to the impl keyword. macro_rules! impl_FooTrait { ($name:ty) => { impl…
Nathan Ringo
  • 973
  • 2
  • 10
  • 30
20
votes
3 answers

Using Attributes for Generic Constraints

Given an example such as .. public interface IInterface { } public static void Insert(this IList list, IList items) where T : IInterface { // ... logic } This works fine, but I was wondering if it is possible to use an Attribute as a…
Ciel
  • 17,312
  • 21
  • 104
  • 199
20
votes
1 answer

Typescript access static attribute of generic type

I have an abstract class Model with a static attribute and another generic class Controller. I want to access the static attribute of Model in an instance of Controller. That should like this: abstract class Model{ static…
Johannes Kees
  • 353
  • 2
  • 6
20
votes
3 answers

Open generic type arguments cannot be inferred from the usage

In this question, when mentioning the compiler, I'm actually referring to the Roslyn compiler. The problem arises when using IntelliSense, which is presumed to be the same compiler. For demonstration purposes and completeness, the following classes…
QuantumHive
  • 5,613
  • 4
  • 33
  • 55
20
votes
1 answer

What does it mean to instantiate a Rust generic with an underscore?

While working with serde_json for reading json documents, I wrote the following line of code to obtain the result of unwrapping the return value of serde_json::from_str: fn get_json_content(content_s: &str) -> Option { let ms: String =…
Plastikfan
  • 3,674
  • 7
  • 39
  • 54
20
votes
3 answers

Cast T parameter in generic method to DateTime

I have the following (simplified) method: private static string GetStringFromValue(T val) { if (typeof(T) == typeof(DateTime)) { return string.Format("{0}", ((DateTime)val).Year.ToString("0000")); } return…
Chris
  • 4,325
  • 11
  • 51
  • 70
20
votes
4 answers

Difference between generic super class and super class type

I can't understand the difference between the two code snippets below. Can someone help me with a simple explanation? First of all, I have to say that I have a lot of classes that extend a super class named BaseEntity, so what are the differences,…
user4018604
20
votes
4 answers

Multiple converters with Retrofit 2

I have a HATEOAS (HAL) REST service and managed to talk to it with the code below (using halarious as a conversion engine) but when I try to merge the converters (stallone and stallone2), the app will always pick up the first converter, instead of…
Gabor
  • 7,352
  • 4
  • 35
  • 56
20
votes
6 answers

What's Wrong with an ArrayList?

Recently I asked a question on SO that had mentioned the possible use of an c# ArrayList for a solution. A comment was made that using an arraylist is bad. I would like to more about this. I have never heard this statement before about arraylists.…
fishhead
  • 5,829
  • 7
  • 32
  • 43
20
votes
10 answers

Shift elements in array by index

Given array of n elements, i.e. var array = [1, 2, 3, 4, 5] I can write an extension to the Array so I can modify array to achieve this output: [2, 3, 4, 5, 1]: mutating func shiftRight() { append(removeFirst()) } Is there a way to implement such…
Richard Topchii
  • 7,075
  • 8
  • 48
  • 115
20
votes
4 answers

Returning an objects subclass with generics

With an abstract class I want to define a method that returns "this" for the subclasses: public abstract class Foo { ... public T eat(String eatCake) { ... return this; } } public class CakeEater…
Sarabjot
  • 489
  • 1
  • 4
  • 13
20
votes
3 answers

Generic Type cast

I have the following class (simplified but still a working example): class Test { List l = new ArrayList<>(); public Test() { } public void add(Object o) { l.add((T)o); } } And the test code: Test t = new…
gregseth
  • 12,952
  • 15
  • 63
  • 96
20
votes
5 answers

How should I cast for Java generic with multiple bounds?

Is it possible to cast an object in Java to a combined generic type? I have a method like: public static void doSomething(T object) { //do stuff } Calling this method is no problem if I have a class that implements both…
pvgoddijn
  • 12,638
  • 15
  • 47
  • 56
20
votes
0 answers

Why is a generic repository considered an anti-pattern?

it seems to me that a lot of specialised repository classes share similar characteristics, and it would make sense to have these classes implement an interface that outlines these characteristics, creating a generic repository to illustrate my…
user2541688