What are some examples of where you would use generics in C#/VB.NET and why would you want to use generics?
Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
For example, you can create a generic method to add two numbers. This method can be used to add two integers as well as two float numbers without any modification to the code. The Generics are type-safe. Generic data types provide better type safety, especially in the case of collections.
Generics add that type of safety feature. We will discuss that type of safety feature in later examples. Generics in Java are similar to templates in C++. For example, classes like HashSet, ArrayList, HashMap, etc., use generics very well.
Simply, you declare a type or method with extra tags to indicate the generic bits:
class Foo<T> { public Foo(T value) { Value = value; } public T Value {get;private set;} }
The above defines a generic type Foo
"of T
", where the T
is provided by the caller. By convention, generic type arguments start with T. If there is only one, T
is fine - otherwise name them all usefully: TSource
, TValue
, TListType
etc
Unlike C++ templates, .NET generics are provided by the runtime (not compiler tricks). For example:
Foo<int> foo = new Foo<int>(27);
All T
s have been replaced with int
in the above. If necessary, you can restrict generic arguments with constraints:
class Foo<T> where T : struct {}
Now Foo<string>
will refuse to compile - as string
is not a struct (value-type). Valid constraints are:
T : class // reference-type (class/interface/delegate) T : struct // value-type except Nullable<T> T : new() // has a public parameterless constructor T : SomeClass // is SomeClass or inherited from SomeClass T : ISomeInterface // implements ISomeInterface
Constraints can also involve other generic type arguments, for example:
T : IComparable<T> // or another type argument
You can have as many generic arguments as you need:
public struct KeyValuePair<TKey,TValue> {...}
Other things to note:
Foo<int>
is separate to that on Foo<float>
.for example:
class Foo<T> { class Bar<TInner> {} // is effectively Bar<T,TInner>, for the outer T }
Example 1: You want to create triple class
Class Triple<T1, T2, T3> { T1 _first; T2 _second; T3 _Third; }
Example 2: A helper class that will parse any enum value for given data type
static public class EnumHelper<T> { static public T Parse(string value) { return (T)Enum.Parse(typeof(T), value); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With