c# optional parameters

I have a function like the following:

public static void Foo(Vector3 foo = Vector3.zero)
{
    //...
}

Which gives me an error: "The expression being assigned to optional parameter 'foo' must be constant or default value."

What am I doing wrong?

I believe the correct way to do it in C# is:

public static void Foo(Vector3 bar = default(Vector3)){
//this will default the Vector3 to 0,0,0
}

In the end I used a nullable type like so:

public static void Foo(Vector3? foo = null)
{
    Vector3 v = foo ?? Vector3.zero;
    // ...
}

Another alternative is to use multiple entry points (method overloads) rather than optional parameters:

public static void Foo()
{
    Foo(Vector3.zero);
}

public static void Foo(Vector3 foo)
{
    //...
}

Also, for more information on optional parameters, see MSDN.

You are passing to the parameter the result of a property or attribute from another class, which C# cannot guarantee if it is really constant at compile-time. All optional parameters in C# must be constant at compile time.

As a workaround, you may do the following (saying out of my head, try it):

public static void Foo(Vector3 foo = new Vector3(0,0,0))
{
    //...
}

or just initialize it inside the class (as Vector3 is nullable), such as:

public static void Foo(Vector3 foo = null)
{
    if (foo == null) foo = Vector3.Zero;
    //...
}

There's also a OptionalParameter class in .NET, which I'm not sure if works under MONO.

There's a link that explains all that: http://msdn.microsoft.com/en-us/library/dd264739.aspx