+ 2

What is a generic classes/method in c#?

I search, watch the course, watch docs but I can't understand the utility

23rd Jan 2020, 4:56 PM
Valerio Falco
Valerio Falco - avatar
6 Respuestas
+ 7
Valerio Falco For those familiar with C++, C# generics are lighter versions of C++ templates. Generics provide the ability to reuse a class or method where type bindings for method signatures, properties, etc can be generically declared with placeholders (ie <T>) that refer to the type to be specified by the client code (ie <int> or <string> or <Foo>). Think of these placeholders as meta type variables containing the type to be used for a method parameter and / or return type or for other variables, properties, fields and such. (continued...)
23rd Jan 2020, 7:14 PM
David Carroll
David Carroll - avatar
+ 6
For example, imagine these simple NON-generic class examples: class StringArray { int Find(string value) {...} } class IntArray { int Find(int value) {...} } class FooArray { int Find(Foo value) {...} } These classes for IntArray, StringArray, FooArray, etc may be defined with the exact same behavior and code... except one is defined with type String, another with type Int32, and another with type Foo, and so on. They would be implemented in the client code as such: var s = new StringArray {"a", "b", "c"} s.Find("b") var i = new IntArray {1, 2, 3} i.Find(2) var fooBar = new Foo("Bar") var fooBoo = new Foo("Boo") var fooBee = new Foo("Bee") var f = new FooArray { fooBar, fooBoo, fooBee } f.Find(fooBoo) Next, let's compare to using generics... (continued...)
23rd Jan 2020, 7:39 PM
David Carroll
David Carroll - avatar
+ 6
The classes in the previous examples can be combined into a single class that can support multiple types by using generic placeholders. class GenericArray<T> where T : IComparable { public int Find(T value) { int Find(T value) {...} } } Notice that <T> is going to be a placeholder for specifying the type from the previous class examples. The type binding occurs when instantiating the classes as seen below: var s = new GenericArray<string> {"a", "b", "c"} s.Find("b") var i = new GenericArray<int> {1, 2, 3} i.Find(2) var fooBar = new Foo("Bar") var fooBoo = new Foo("Boo") var fooBee = new Foo("Bee") var f = new GenericArray<Foo> { fooBar, fooBoo, fooBee } f.Find(fooBoo) Essentially, the client code looks mostly the same, except for using the same array class type with different <T> bindings. Hopefully, this makes sense and will help you move forward when reviewing other resources like the link below. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/
23rd Jan 2020, 7:51 PM
David Carroll
David Carroll - avatar
+ 4
David Carroll should be able to help you with this
23rd Jan 2020, 6:24 PM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 3
thanks for the excellent and clear explanation
23rd Jan 2020, 8:01 PM
Valerio Falco
Valerio Falco - avatar
0
Hat bhosdike
11th May 2021, 1:16 PM
Neel wanelkar
Neel wanelkar - avatar