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

Typescript: constrain argument of function to be a key of an object associated with a value of a particular type

Is there a way to make the following type check? function getNumberFromObject(obj: T, key: keyof T): number { return obj[key] // ERROR: obj[key] might not be a number } I want to specify that key should not only be a key of T, but a key with a…
Lionel Tay
  • 1,274
  • 2
  • 16
  • 28
18
votes
4 answers

What is the difference between A and A?

I am a new java learner. Recently I was reading Generic programming and got my self confused with this... A and A
arpanoid
  • 2,123
  • 4
  • 17
  • 15
18
votes
4 answers

How did generics influence the design of C# and .NET?

This might be a broad question but this is something I am not really clear and very curious. Often times for certain problems I hear the reasoning that it was because Generics was not available in .NET 1.0. That makes me think either of these 2…
Joan Venge
  • 315,713
  • 212
  • 479
  • 689
18
votes
2 answers

MultiMap in Scala

I'm trying to mixin the MultiMap trait with a HashMap like so: val children:MultiMap[Integer, TreeNode] = new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode] The definition for the MultiMap trait is: trait MultiMap[A, B]…
sblundy
  • 60,628
  • 22
  • 121
  • 123
18
votes
4 answers

Java Generics - to

In the way of learning Java Generics, I got stuck at a point. It was written "Java Generics works only with Objects and not the primitive types". e.g Gen gen=new Gen(88); // Works Fine .. But, with the primitive types…
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
18
votes
2 answers

Make an extensions of generic class in Swift4

Lets assume we have a simple generic class: class Foo { } next add to this class an extension which implements UITableViewDatasoure: extension Foo: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection…
Kamil Harasimowicz
  • 4,684
  • 5
  • 32
  • 58
18
votes
1 answer

Type-safe mixin decorator in TypeScript

I tried to define type-safe mixin() decorator function like follows, type Constructor = new(...args: any[]) => T; function mixin(MixIn: Constructor) { return function decorator(Base: Constructor) : Constructor { …
Kiikurage
  • 195
  • 1
  • 6
18
votes
3 answers

What is the equivalent of C#'s `default` in VB.NET?

I'm normally at home in C#, and I'm looking at a performance issue in some VB.NET code -- I want to be able to compare something to the default value for a type (kind of like C#'s default keyword). public class GenericThing { public T1…
Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
18
votes
6 answers

What unit test to write for a class using generics in Java?

Taking the very specific example of the JpaDao class defined in this article: public abstract class JpaDao implements Dao { protected Class entityClass; @PersistenceContext protected EntityManager entityManager; …
Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
18
votes
4 answers

Java generics and array initialization

What's the explanation for the following: public class GenericsTest { //statement 1 public ArrayList[] lists; public GenericsTest() { //statement 2 lists = new ArrayList[4]; } } The…
Steve B.
  • 55,454
  • 12
  • 93
  • 132
18
votes
1 answer

How do I write this member constraint in F#?

For a type type Cow() = class member this.Walk () = Console.WriteLine("The cow walks.") end I can write a method which enforces a member constrain for method Walk like let inline walk_the_creature creature = (^a : (member Walk…
SharePoint Newbie
  • 5,974
  • 12
  • 62
  • 103
18
votes
2 answers

What's the difference between using or not using the 'where' clause with generics?

What's the difference between these two methods of declaring a generics superclass with or without the 'where' clause? func foo(object: T) -> Array func foo(object: T) -> Array where T: SomeClass
Mattia C.
  • 700
  • 1
  • 5
  • 15
18
votes
3 answers

Second order generics seem to behave differently than first order generics

I thought I have a reasonable grasp of generics. For example, I understand why private void addString(List list, String s) { list.add(s); // does not compile list.add(list.get(0)); // doesn't compile either } Does not…
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
18
votes
2 answers

Mocking generic methods

Assume I have some interface with a generic method and no parameters: public interface Interface { void Method(); } Now I wish to implement the mock for this class (I'm using Moq) and I wish to mock this method for some concrete type - let's…
Yippie-Ki-Yay
  • 22,026
  • 26
  • 90
  • 148
18
votes
1 answer

How to add a generic dependency injection

Working on a read-only api service and making use of generics to package the operation into convention based process. Repository interface: public interface IRepository where TEntityType:class { Task>…
Vijay
  • 578
  • 2
  • 5
  • 15
1 2 3
99
100