- Home /
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?
Answer by justinl · Sep 21, 2012 at 11:55 AM
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
}
I believe this is the correct way as well, this should be thumbed up as the answer so others can benefit, it's the most elegant solution.
can't upvote yet, but this answer worked for me. thanks!
Yup, correct way, but doesn't always work (for example in extension methods) because Unity does weird things with its internal structs :/
You can leave out the type argument for the default
as it can be implied. Foo(Vector3 bar = default)
works
Answer by Matthew A · Jan 28, 2011 at 02:32 PM
In the end I used a nullable type like so:
public static void Foo(Vector3? foo = null)
{
Vector3 v = foo ?? Vector3.zero;
// ...
}
Can this be used for the Color class like this?
void DrawWire(Vector2 pr1, Vector2 pr2, Color color, Color? shadowColor = null)
Answer by yoyo · Jan 28, 2011 at 05:06 PM
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.
Answer by zharramadar · Jan 28, 2011 at 01:54 PM
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
Thanks for the answer, you put me on the right track, though new Vector3(0,0,0) didn't work either.
Yeah, I'm at work, so I couldn't test it in Unity. Glad it worked with the nullable thing.
The first method does not work me; it generates the same error as the original question.
Old answer, but still deserves to be noted that Vector3 is a struct and thus is NOT nullable, and the other option doesn't work because optional parameters need to be compile-time constants, so it's all wrong :P