Home > Net >  C# Class constructor that can take type int OR float
C# Class constructor that can take type int OR float

Time:10-27

I would like to have a class Stat be able to take in (int value) or (float value)

The reason for this being that I want to create a Dictionary(string, Stat) so I can't make two classes. I also have functions in the class for levelling up and resetting the stat, so I can't make multiple constructors.

I can edit in my code if it would help, but I believe I have described the issue well enough. I am using Unity so I am locked at C# version 8.0

Edit: If this seems like a stupid question I apologise. I am entirely self taught so I don't know some stuff. Also I did do a lot of searching before posting this question, but there were no solutions that I could find.

Edit(2): My question was unclear. My end goal is something like this:

Dictionary stats = new Dictionary(string, Stat)
{
    {"health", Stat(int 30)}
    {"attack", Stat(float 2.5)}
    ...
}

A list of stats that can be either int or float, for the sake of performance.

CodePudding user response:


The answer was simple. Thanks to @UnholySheep for discussing this with me. This answer is a summary of the comments beneath the question above (saved here in the event they are deleted).


UnholySheep:

you could make Stat and interface or (abstract) base class and have two classes that inherit from it.

Concerns over performance most likely don't apply, again from Mr Sheep:

You'd need some quite extreme numbers for the floating point performance to become a real bottleneck

In none of the games I have worked on the stats system was ever a bottleneck. Discussions of float vs int performance only make sense in systems that have to perform a lot of calculations.

As for class design vs dictionaries, a simple class with embedded fields will suffice:

we never used a Dictionary to store the stats either, just a class with the types of stats being member fields makes a lot more sense, since the stats have to be defined all throughout code to be useful anyway

  • Related