C
C#2y ago
Dean

❔ Is a generic with a where clause equivalent to passing the same type through as a parameter

Is there any difference between the following 2 methods? public void DoSomething<T>(T value) where T : class, IComparable { int result = value.CompareTo(10); Console.WriteLine(result); } public void DoSomething(IComparable value) { int result = value.CompareTo(10); Console.WriteLine(result); }
14 Replies
mtreit
mtreit2y ago
The first one disallows value types
cathei
cathei2y ago
Second one boxes value type
Dean
DeanOP2y ago
do you mean the first one can't be a struct that inherits the interface, and that is due to the class keyword?
mtreit
mtreit2y ago
Yes
Anton
Anton2y ago
class means reference type
Dean
DeanOP2y ago
I asked an AI and it told me this, it doesn't seem true, is it? in the first example the DoSomething method can be called with any class that implements the IComparable interface. The method can then use the CompareTo method of the IComparable interface to compare the value to the number 10. by contract (second example), if you used a specific type (such as IComparable) as a parameter, you would not be able to use the type parameter as a placeholder within the method implementation. Instead, you would need to use the specific type (such as IComparable) directly:
mtreit
mtreit2y ago
You generally don't want to use the non-generic IComparable interface.
Dean
DeanOP2y ago
you mean don't use the second method?
mtreit
mtreit2y ago
They're both using the non-generic version IComparable<T> is usually what you want Although in your example you are hard-coding comparison to int so it's kind of unclear what your actual scenario is.
Dean
DeanOP2y ago
why would it be boxed? why use the generic version?
mtreit
mtreit2y ago
To avoid boxing Because the non-generic version takes it's input as type object
Dean
DeanOP2y ago
ahh i see so specifying the type can avoid it how do you remember this is icomparable used often?
mtreit
mtreit2y ago
IComparable<T> is used when you need something to be sortable...so for types with that requirement yes its used quite often
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server