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

How generics in java works for the following program?

public class Program { private static void foo(Program x){ System.out.println(x+"-->1"); } private static void foo(final int i){ System.out.println(i+"-->2"); } public static void main(String[] args)…
19
votes
2 answers

Swift-Generics: "Cannot specialize non-generic type"

I try to implement object oriented code by using a generic protocol. Lets say I have two protocols protocol Executable: class { func execute() } protocol Dockable: class { associatedtype T func dock(object: T) } I've implemented a…
ObjectAlchemist
  • 1,109
  • 1
  • 9
  • 18
19
votes
3 answers

Why does a generic method inside a trait require trait object to be sized?

I have this code (playground): use std::sync::Arc; pub trait Messenger : Sync + Send { fn send_embed String>(&self, u64, &str, f: F) -> Option where Self: Sync + Send; } struct MyMessenger { prefix:…
VP.
  • 15,509
  • 17
  • 91
  • 161
19
votes
3 answers

Java: Casting Object to a generic type

In Java when casting from an Object to other types, why does the second line produce a warning related to the cast, but the first one doesn't? void a(Object o) { Integer i = (Integer) o; List list = (List) o; } /*Type safety:…
Mike
  • 58,961
  • 76
  • 175
  • 221
19
votes
2 answers

References to generic functions

Is it possible to make reference to generic functions in Kotlin? For example, let's say I have a function: fun inline appendToString(a: T, b: T) = a.toString() + b.toString How can you reference this function? This will not compile var…
SilverCorvus
  • 2,956
  • 1
  • 15
  • 26
19
votes
1 answer

Why does ToString() on generic types have square brackets?

Why does new List().ToString(); return the following:? System.Collections.Generic.List`1[System.String] Why wouldn't it just bring back System.Collections.Generic.List. What's with the strange non C# syntax?
David Klempfner
  • 8,700
  • 20
  • 73
  • 153
19
votes
3 answers

How do I constrain a Kotlin extension function parameter to be the same as the extended type?

I want to write an extension method on a generic type T, where the matched type constrains a method parameter. I want this to compile: "Hello".thing("world") But not this, as 42 is not a String: "Hello".thing(42) This definition doesn’t work,…
Duncan McGregor
  • 17,665
  • 12
  • 64
  • 118
19
votes
3 answers

How to inject dependencies of generics in ASP.NET Core

I have following repository classes: public class TestRepository : Repository { private TestContext _context; public TestRepository(TestContext context) : base(context) { _context = context; } } public abstract class…
Palmi
  • 2,381
  • 5
  • 28
  • 65
19
votes
3 answers

How to store delegates in a List

How can I store delegates (named, anonymous, lambda) in a generic list? Basically I am trying to build a delegate dictionary from where I can access a stored delegate using a key and execute it and return the value on demand. Is it possible to do in…
Anindya Chatterjee
  • 5,824
  • 13
  • 58
  • 82
19
votes
4 answers

WPF UserControl with generic code-behind

I have this code behind: CustomUserControl.xaml.cs namespace MyProject { public partial class CustomUserControl : UserControl { ... } } and this xaml: CustomUserControl.xaml
Bob
  • 273
  • 1
  • 3
  • 7
19
votes
6 answers

A generic singleton

What do you guys think about this for a generic singleton? using System; using System.Reflection; // Use like this /* public class Highlander : Singleton { private Highlander() { Console.WriteLine("There can be only…
Simon Hughes
  • 3,534
  • 3
  • 24
  • 45
19
votes
2 answers

Why super keyword in generics is not allowed at class level

In Generics class A is allowed But class A is not allowed I'm not getting this point. This may sound like novice question but I'm stuck in it
bananas
  • 1,176
  • 2
  • 19
  • 39
19
votes
7 answers

Swift - Take Nil as Argument in Generic Function with Optional Argument

I am trying to create a generic function that can take an optional argument. Here's what I have so far: func somethingGeneric(input: T?) { if (input != nil) { print(input!); } } somethingGeneric("Hello, World!") // Hello,…
Coder-256
  • 5,212
  • 2
  • 23
  • 51
19
votes
1 answer

Writing a generic function that takes an iterable container as parameter in Rust

I want to write a generic function that takes any immutably borrowed iterable container such as an array, Vec, BTreeSet, etc. Since this function is part of a trait that I am implementing, I am not able to change the signature of it, so it's not…
Zoidberg
  • 228
  • 2
  • 9
19
votes
3 answers

How to implement generic GetById() where Id can be of various types

I am trying to implement a generic GetById(T id) method which will cater for types which may have differing ID types. In my example, I have an entity which has an ID of type int, and one of type string. However, I keep getting an error and I have no…
Tomuke
  • 869
  • 2
  • 8
  • 26