0

I am attempting to make a suvat calculator and require to have some form of way to have two different types of variable stored in one variable.

For those unaware of suvat. suvat equations are a collection of equations which allows for each of the five variables to be found from only three known variables.

This means that I need to be able to have a variable hold a float and a null value. Is there any way of doing this?

2 Answers2

3

In order for a variable to hold both a float or null, you need to use nullable types. For example, you can use "float?" as the type:

float? myFloat = null;

If you need to hold a double or null, use the nullable double type:

double? myDouble = null;

etc.

BoltBait
  • 11,361
  • 9
  • 58
  • 87
  • Also known as "[Nullable types](https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx)". – Uwe Keim Mar 25 '17 at 19:54
  • Unfortunately, this is pretty much what I need; however, I cannot seem to convert this type to a double. Each conversion I try doesn't allow me to use Math.sqrt(variable) – TheAndOnlyFin Mar 25 '17 at 20:35
  • @TheAndOnlyFin, after testing to be sure myFloat doesn't equal null, try: Math.Sqrt((double)myFloat); – BoltBait Mar 25 '17 at 20:44
0

You can simply create a class that contains the types you need. For example, if you need a float and a string (you said null, but that is not a type, so I'm using string, which can be null):

class SomeClassName
{
    public float FloatValue {get; set;}
    public string StringValue {get; set;}
}

Now you can create a variable of type SomeClassName and assign it both a float and a string:

SomeClassName suvat = new SomeClassName();
suvat.FloatValue = 1.2;
suvat.StringValue = null;
Rufus L
  • 36,127
  • 5
  • 30
  • 43