+ 2
What is a generic classes/method in c#?
I search, watch the course, watch docs but I can't understand the utility
6 odpowiedzi
+ 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...)
+ 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...)
+ 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/
+ 4
David Carroll should be able to help you with this
+ 3
thanks for the excellent and clear explanation
0
Hat bhosdike