I created a specialization for a generic like code below:
public class BaseGeneric<T>
{
public static T DoStuff()
=> default;
}
public class SpecializedFromBaseGeneric : BaseGeneric<int>
{
public static new int DoStuff()
=> 789;
}
Now to call the DoStuff()
method I would like to use var result = BaseGeneric<int>.DoStuff();
When I run this code, result
is 0
instead of 789
. The debugger shows that the call will enter the DoStuff()
from public class BaseGeneric<T>
instead of SpecializedFromBaseGeneric
.
What am I doing wrong?
Later edit
I also tried to create specialization in the below format but that does not even compile:
public class BaseGeneric<T> where T : int
{
public static T DoStuff()
=> 789;
}
I want to do several specializations and use the call similar to the one specified above for int
data type BaseGeneric<int>.DoStuff()
. And for each specialization use the same syntax where only data type is changed but different implementation is used (eg: for string that would be BaseGeneric<string>.DoStuff()
). How to achieve this behaviour?
CodePudding user response:
public class BaseGeneric<T> where T : IConvertible
{
public static T DoStuff()
{
if (typeof(T) == typeof(int))
{
return (T)(object)789;
}
if (typeof(T) == typeof(string))
{
return (T)(object)"ss";
}
return default(T);
}
}
However, as the asnwer here suggests, this is brittle, and doesn't cover every possible usage.
CodePudding user response:
var result = BaseGeneric<int>.DoStuff()
This one calls the function of a base class. It returns new T(), that equals new int(), that equals zero.
var result = SpecializedFromBaseGeneric.DoStuff()
This one will return what you need.