❔ 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
The first one disallows value types
Second one boxes value type
do you mean the first one can't be a struct that inherits the interface, and that is due to the class keyword?
Yes
class
means reference typeI 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:
You generally don't want to use the non-generic IComparable interface.
you mean don't use the second method?
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.
why would it be boxed?
why use the generic version?
To avoid boxing
Because the non-generic version takes it's input as type object
ahh i see so specifying the type can avoid it
how do you remember this
is icomparable used often?
IComparable<T> is used when you need something to be sortable...so for types with that requirement yes its used quite often
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.