C
C#5mo ago
vanille.

Change function behavior depending on class' generic type.

Hello! I was wondering if there was a way to change the behavior of a function in a class with a generic type. I was originally looking into overloading but didn't have any luck. Is what I'm trying to do possible?
public class Lerpable<T>
{
private readonly T _value1;
private readonly T _value2;

public Lerpable<T> (T value1, T value2)
{
_value1 = value1
_value2 = value2
}

public T Lerp(float amount)
{
// Default behavior, I want to be able to change this depending on what T is.
return amount > 0.5 ? _value2 : _value1;
}
}
public class Lerpable<T>
{
private readonly T _value1;
private readonly T _value2;

public Lerpable<T> (T value1, T value2)
{
_value1 = value1
_value2 = value2
}

public T Lerp(float amount)
{
// Default behavior, I want to be able to change this depending on what T is.
return amount > 0.5 ? _value2 : _value1;
}
}
10 Replies
Jimmacle
Jimmacle5mo ago
you'd have to compare typeof(T) to the types you're interested in what's the end goal? if you're only interested in numbers you can use the INumber<T> interface as a constraint
vanille.
vanille.5mo ago
(Color is from Microsoft.Xna.Framework)
public T Lerp(float amount)
{
if (typeof(T) == typeof(Color)) {
return Color.Lerp(_value1, _value2, amount);
}
return amount > 0.5 ? _value2 : _value1;
}
public T Lerp(float amount)
{
if (typeof(T) == typeof(Color)) {
return Color.Lerp(_value1, _value2, amount);
}
return amount > 0.5 ? _value2 : _value1;
}
Can't, since if i have it inside of the function, the compiler won't be able to convert T into Color.
Jimmacle
Jimmacle5mo ago
yeah that's about all you can do then, though you could also pattern match on _value1 or _value2 since you have those available e.g. if (_value1 is Color color1)
vanille.
vanille.5mo ago
Still having a conversion issue, mainly with setting color1 to _value1.
Gruhlum
Gruhlum5mo ago
sounds like a job for extensions.
public static class Extensions
{
public static Color Lerp(this Color color)
{
return color;
}
}
public static class Extensions
{
public static Color Lerp(this Color color)
{
return color;
}
}
vanille.
vanille.5mo ago
Color.Lerp() is already a member of the class. ...I don't understand this answer.
Jimmacle
Jimmacle5mo ago
you might have to do some sketchy unsafe things to force this pattern to work PepeHmmm
vanille.
vanille.5mo ago
MarinePensive
Jimmacle
Jimmacle5mo ago
like Unsafe.As which is a type cast that ignores any safety checks
vanille.
vanille.5mo ago
I'll just do it the original way I had planned, making inherited classes like LerpableColor : Lerpable<Color>. Thank you for the help though. mikuarigathanks