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
1 answer

Generic wildcards in variable declarations in Scala

In Java I might do this: class MyClass { private List list; public void setList(List l) { list = l; } } ...assuming that (MyImpl implements MyInterface) of course. What is the analog for this in Scala, when…
oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
20
votes
3 answers

Generic class with self-referencing type constraint

Consider the following code: abstract class Foo where T : Foo, new() { void Test() { if(Bar != null) Bar(this); } public event Bar Bar; } delegate void Bar(T foo) where T : Foo,…
Nathan Ridley
  • 33,766
  • 35
  • 123
  • 197
20
votes
2 answers

Improve Binary Serialization Performance for large List of structs

I have a structure holding 3d co-ordinates in 3 ints. In a test I've put together a List<> of 1 million random points and then used Binary serialization to a memory stream. The memory stream is coming in a ~ 21 MB - which seems very inefficient as…
Ryan
  • 23,871
  • 24
  • 86
  • 132
20
votes
8 answers

Remove object from generic list by id

I have a domain class like this: public class DomainClass { public virtual string name{get;set;} public virtual IList Notes{get;set;} } How would I go about removing an item from the IList? I would be able to do it if it was a List…
gdp
  • 8,032
  • 10
  • 42
  • 63
20
votes
3 answers

Why does Java's Collection.toArray() return an Object[] rather than an E[]?

Before Java generics, Collection.toArray() had no way to know which type of array the developer expected (particularly for an empty collection). As I understand it, this was the main rationale behind the idiom collection.toArray(new E[0]). With…
20
votes
2 answers

.NET - Getting all implementations of a generic interface?

An answer on " Implementations of interface through Reflection " shows how to get all implementations of an interface. However, given a generic interface, IInterface, the following doesn't work: var types =…
David Pfeffer
  • 38,869
  • 30
  • 127
  • 202
20
votes
3 answers

How to convert vararg to list?

I have a function with a vararg parameter. This vararg parameter needs to be passed to another function as a list. How do I convert the vararg param into a list? listOf() gave me an error. fun insertMissingEntities(vararg entities: Entity) { val…
Terry
  • 14,529
  • 13
  • 63
  • 88
20
votes
3 answers

Typescript generic class equivalent for React.memo

Is there any way to set new generic in React.memo? For example, for class components, I can use // set generic class GenericClass extends PureComponent {} // and use like this /> In the below…
Thu San
  • 1,400
  • 1
  • 17
  • 29
20
votes
9 answers

Retrieving type parameters from an instance of a generic base interface

Given 2 interfaces: public interface BaseInterface { } public interface ExtendedInterface extends BaseInterface {} and a concrete class: public class MyClass implements ExtendedInterface { } How do I find out the…
Andy
  • 3,596
  • 8
  • 34
  • 33
20
votes
1 answer

Swift 5 LLDB error: warning: :12:9: warning: initialization of variable '$__lldb_error_result' was never used

Full Error Message: error: warning: :12:9: warning: initialization of variable '$__lldb_error_result' was never used; consider replacing with assignment to '_' or removing it var $__lldb_error_result = __lldb_tmp_error …
andrewbuilder
  • 3,629
  • 2
  • 24
  • 46
20
votes
2 answers

Passing int[][] as generic parameter

public static void func1(T[][] arr) { ... } public static void func2(T[] arr) { ... } I'm trying to pass a 2-dimensional array, int[][] arr. I cannot use func1(arr) , but I can use func2(arr) Can someone explain me how this works?
Sumit Das
  • 1,007
  • 9
  • 17
20
votes
2 answers

Annotation Processor appears to break Java generics

Background I was trying to use Annotation Processors, to generate implementations of specific Factory interfaces. Those interfaces look the following: public interface ViewFactory { > T create(S…
Thorben Kuck
  • 1,092
  • 12
  • 25
20
votes
4 answers

Checking if an object meets a Generic Parameter constraint

I have an interface similar to the one below: public interface IInterface where T : IInterface { } And now I need to create a type representing this interface using reflection,…
Simon
  • 5,373
  • 1
  • 34
  • 46
20
votes
3 answers

How to get property of generic type?

I have an abstract class, in the method of which I am passing an item of a generic type. Next, I need to get the property of this item, how to do it correctly? export abstract class BaseService { ... public saveItem(item: T) { …
Green176
  • 349
  • 2
  • 3
  • 9
20
votes
3 answers

How to write lambdas with generics in kotlin?

I can write lambdas id_Int and id_Boolean with explicit type. And I can write function identity with type parameter. Can I write lambdas with type parameter? fun testFuncInt(f: (Int) -> Int): Int = f(1) + 2 val id_Int = { x: Int -> x } fun…
xiang
  • 1,384
  • 1
  • 12
  • 28