Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 51 / 68

Writing Generic Functions

In this lesson you will learn how to write generic functions in C#, so one method can work with several types. This is for anyone searching for "C# generics how to use".

Generics (<T>) let you write a method that works with any type instead of committing to one. That is useful when you want the same logic for numbers and for strings.

The sample code defines static T Larger<T>(T a, T b) where T : IComparable, so both the numeric Larger(3, 7) and the string Larger("apple", "banana") go through the same method. The where T : IComparable constraint is what restricts it to comparable types.

A common stumbling block for beginners is why the constraint is needed at all. A where clause lets you accept only comparable types; with a bare T and no constraint there is no guarantee that comparison operators are available.

In real-world development, the generic collections List<T> and Dictionary<TKey,TValue> are built on this same mechanism.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)