C# XNA Xbox, in this case optional parameters are not optional-Collection of common programming errors
Apparently optional parameters won’t work in C# Xna when used on the Xbox, there non suportedness is stated during compilation.
I have a situation like this:
func(float? a = null, int? b = null)
With large numbers of thease optional parameters that default to the “undefined” value, null. This situation is required.
In the simplified example above this can be unwrapped, although this isn’t as optional parameters allow:
func()
func(float? a)
func(int? b)
func(float? a, int? b)
However with large numbers of parameters this isn’t practical.
Some combinations of parameters definedness isn’t permitted and results in paths through the function where I throw argument exceptions, others result in various different things occurring depending on the values of the parameters. This is similar to polymorphism between functions with the same name but is not the same.
I could alternatively, and probbably most practically, require all the parameters instead.
func(float? a, int? b)
Then call as so:
func(null, 4)
Where the first is undefined.
Instead of using one of the above bodges, is there a way to enable optional parameters in C# XNA on Xbox?
-
I would use old-fashioned overloads that take different numbers of parameters, and forward the calls on from there, along with the “default” values. Zero code changes to the callers.
If the types are outside your control: extension methods to add the overloads.
-
I don’t think you can enable the optional parameters. Maybe you can use an alternative. like the params keyword that creates an array, you could just pass an object as parameter
public class MyParams { public float? a {get;set;} public int? b {get;set;} } func(new MyParams { b = 5 });
With that solution, you have all the flexibility you might want. You can add, remove parameters without thinking of adding/removing new overload. And if you remove or edit a parameter, you’ll get a compile time error, something you might not get with multiple overload.
Originally posted 2013-11-09 19:01:50.