'C# Non-generic method in generic class
Am trying to define a class that provides a random number between two values. It shall work with ints as well as with floats.
To only have a single class, I'd like to use generics. This works well for the member variables, but how do I define a method for only specific types?
The Random.Range method I use (from unity) can accept floats or ints so a cast is needed. The generic type does not seem to be castable at all however.
Have written this code to show what I am looking for. Does a syntax similar to this exist?
public class MinMaxSetting<T>
{
public T min;
public T max;
public MinMaxSetting(T min_val, T max_val)
{
min = min_val;
max = max_val;
}
public T GetRandom<int>()
{
return Random.Range((int)min, (int)max);
}
public T GetRandom<float>()
{
return Random.Range((float)min, (float)max);
}
}
Solution 1:[1]
Found a solution: Extension Methods!
Surely a bit quirky but it does what it's supposed to and it's readable.
public class MinMaxSetting<T>
{
public T min;
public T max;
public MinMaxSetting(T min_val, T max_val)
{
min = min_val;
max = max_val;
}
}
// Helper class just for the extension methods. The name is irrelevant.
public static class MinMaxSetting
{
public static float GetRandom(this MinMaxSetting<float> self)
{
return UnityEngine.Random.Range(self.min, self.max);
}
public static int GetRandom(this MinMaxSetting<int> self)
{
return UnityEngine.Random.Range(self.min, self.max);
}
}
Example:
public static void Main()
{
MinMaxSetting<float> my_setting = new MinMaxSetting<float>(5.3f, 20.4f);
Console.WriteLine(my_setting.GetRandom());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DragonGamer |
