0.0f vs default(float) vs new float()

float x = 0.0f;
float y = default(float);
float z = new float();
x, y and z are all equal to 0.0, but what are the differences between them? (about the way how it’s assigned)

There is actually almost no difference. The z-variant you really don’t want to use for primitive datatypes as most programmers think of structs or classes when seeing the new keyword.

The y-variant actually plays an important role when it comes to generic classes / methods.
Example:

public class SomeGenericClass<SomeType>
{
    private SomeType someVar = default(SomeType);
    public SomeType DoStuff()
    {
        // ...
        return someVar;
    }
}

A generic class like that which is ment to be used with int, float, double, can’t simply use “0” / “0.0” / “0.0f” to initialize the member variable as the type depends on the generic parameter. “default” allows to pick the default value for the given type. For reference types (classes) this is actually “null”

In general for float values you should simply use your “x-variant” as it’s much easier to read. Keep in mind that you can also use:

float x = 0f;
float x = .0f;

However i prefer “0.0f” :slight_smile: