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
18
votes
3 answers

Can you use generics methods in C# if the type is unknown until runtime?

Easiest way to explain what I mean is with a code sample. This doesn't compile, but is there any way to achieve this effect: foreach(Type someType in listOfTypes) { SomeMethod(); } Would be really convenient if that would work, but…
Davy8
  • 30,868
  • 25
  • 115
  • 173
18
votes
5 answers

How to implement a generic `max(Comparable a, Comparable b)` function in Java?

I'm trying to write a generic max function that takes two Comparables. So far I have public static > T max(T a, T b) { if (a == null) { if (b == null) return a; else return b; } if (b == null) …
Duncan McGregor
  • 17,665
  • 12
  • 64
  • 118
18
votes
8 answers

Removing alternate elements in a List

What is the most efficient way to remove alternate (odd indexed or even indexed) elements in an List without using a place holder list variable? Also it would be appreciated if you could mention the cost with each of your answer. I'm looking…
abhilash
  • 5,605
  • 3
  • 36
  • 59
18
votes
3 answers

System.Collections.Generic.Dictionary `Add` vs set `Item`

If i wish to put items into a System.Collections.Generic.Dictionary, I can either Add or set the Item. I know if we do Add it checks if the key already exists and if not it throws an exception. So when adding a ton of items, should I prefer setting…
Pacerier
  • 86,231
  • 106
  • 366
  • 634
18
votes
5 answers

Can I convert the following code to use generics?

I'm converting an application to use Java 1.5 and have found the following method: /** * Compare two Comparables, treat nulls as -infinity. * @param o1 * @param o2 * @return -1 if o1<o2, 0 if o1==o2, 1 if o1>o2 */ protected…
Steve Bosman
  • 2,599
  • 1
  • 25
  • 41
18
votes
3 answers

Typescript remove first argument from a function

I have a possibly weird situation that I'm trying to model with typescript. I have a bunch of functions with the following format type State = { something: any } type InitialFn = (state: State, ...args: string[]) => void I would like to be able…
MDalt
  • 1,681
  • 2
  • 24
  • 46
18
votes
1 answer

Why Rust don't use default generic parameter type

I want to create generic structure with default type. But Rust compiler still requires me to specify explicit type when creating my structure. struct A {} struct C { t: Option } fn main() { let c = C { t: None }; } Rust compiler…
Michael Ilyin
  • 717
  • 8
  • 15
18
votes
3 answers

Is there Boxing/Unboxing when casting a struct into a generic interface?

Possible Duplicate: Structs, Interfaces and Boxing From the MSDN: http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx Boxing is the process of converting a value type to the type object or to any interface type implemented by this value…
paercebal
  • 81,378
  • 38
  • 130
  • 159
18
votes
3 answers

Why can't `&(?Sized + Trait)` be cast to `&dyn Trait`?

In the code below it is not possible to obtain a reference to a trait object from a reference to a dynamically-sized type implementing the same trait. Why is this the case? What exactly is the difference between &dyn Trait and &(?Sized + Trait) if I…
w1th0utnam3
  • 963
  • 7
  • 19
18
votes
4 answers

Uses of T extends U?

Lately I encountered a method defined similar to this and I don't exactly understand its usage: public static T foo(U u) { ... } A sample use could be like this: // Baz is just the containing class of foo() Number n =…
Lino
  • 19,604
  • 6
  • 47
  • 65
18
votes
3 answers

Does .Net support curried generics?

Suppose we have a nested generic class: public class A { public class B { } } Here, typeof(A.B<>) is in essence a generic class with two parameters where only the first is bound. If I have a single class with two parameters public…
configurator
  • 40,828
  • 14
  • 81
  • 115
18
votes
0 answers

Why does an existential type require a generic instead of an associated type?

I have an existential type defined like this: trait Collection { type Element; } impl Collection for Vec { type Element = T; } type Existential = impl Collection; A function, which takes a type implementing a trait…
Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69
18
votes
1 answer

How to avoid repetitive long generic constraints in Rust

I'm trying to make my own implementation of big integers (just for education). The implementation is generic by data type: struct LongNum where T: Integer + MulAssign + CheckedMul + CheckedAdd + Copy + From { values: Vec, powers:…
Michael Ilyin
  • 717
  • 8
  • 15
18
votes
3 answers

Get generic type of call to method in dynamic object

I'm starting to work with dynamic objects in .Net and I can't figure out how to do something. I have a class that inherits from DynamicObject, and I override the TryInvokeMember method. e.g. class MyCustomDynamicClass : DynamicObject { public…
willvv
  • 8,439
  • 16
  • 66
  • 101
1 2 3
99
100