Getting a generic int, string, float

Is there a way to get a int, string, float in a generic statement?

Such as:

public void DoSomething<T>(T value) where T: stuct
{
if (value.Type == string)
{
//do something
}
}

Or am I approaching this wrong? Should I use something else for this?

You can check the type of the value with the is operator.

if (value is string) { ...}
else if (value is int) { ... }
else if (value is float) { ... }
1 Like

What are you trying to do? Whenever you have to do something different depending on a type there are often better ways of doing it than a bunch of if statements.

1 Like

I’m trying to sort out a string, int, and float. Is there a better way?

I mean what are you trying to accomplish once you know the type?

Saving it via playerPrefs, I think I’m doing it wrong though as it can’t save type T as a float,int,string.

public static void Save <T>(string what, T value)
    {
        if (value is float)
        {
            PlayerPrefs.SetFloat("i" + what, value);
        }
    }

Just create multiple methods…

void Save(string key, float value)
{
  PlayerPrefs.SetFloat(...);
}

void Save(string key, int value)
{
  PlayerPrefs.SetInt(...);
}

... etc...

The methods look the same when you call them…

Save("myfloat", 1.0f);
Save("myInt", 1);

The compiler will pick the appropriate one for you depending on the data type.

3 Likes

I never new you could do that! Thanks! :slight_smile:

Yep, methods can have the same name as long as the parameters are different in number and/or type - it has to be a unique “method signature”.

1 Like

Function overloading - Wikipedia :slight_smile:

2 Likes

I probably should rewatch alot of those tutorials about scripting… I always forget things like this (and syntax for a coroutine)! :stuck_out_tongue:

System.String (string), System.Single (float), and System.Int32 (int) all implement the IConvertible interface. So:

public void DoSomething<T>(T value) where T : IConvertible {
...
}

is probably what you want.

1 Like