C# 4 Optional Parameters Limits Default Value

Jon Skeet has an excellent C# 5 talk video from the recent Norwegian Developer Conference. Go watch it.

When he showed Default<T>, I immediately thought it was just an variation of Option<T> or F#’s option type, but with added default value logic. Its cool.

He was asking for compiler support so that things like this would be possible.

Default<int> a = 1;

Well, I thought, you don’t need compiler support for that, just add an implicit type converter to your definition of Default<T>

        public static implicit operator Default<T>(T value)
            return new Default<T>(value);

No worries, right?

Oh I was so wrong. While this will work for the regular above statement, it won’t work as a default parameter value.

     class Things { public Things(Default<int> a = 5) { } }

This provides a wonderfully descriptive error (I love this compiler) which says “a value of type ‘int’ cannot be used as a default parameter because there are no standard conversions to the type ‘Default<int>’”

Now I’m crying? Why the limit? Instead of Jon’s request for awesome Default<T> support in C# 5, I request considering implicit type converters on optional parameter default values.

2 thoughts on “C# 4 Optional Parameters Limits Default Value”

  1. Jay, the compiler would be calling that implicit operator on the call site.

    class Things { public Things(Default a = 5) { } }

    is compiled to

    class Things { public Things([Optional] Default a) { } }

    and callable as

    new Things(Default.op_implicit(5));

  2. Yes, it’s definitely another use for the Option idea… but I’m not surprised it doesn’t work at the moment. Basically you would need to overhaul the way that default values work in .NET in general – although I believe it would be feasible to support both approaches at the same time. The current system is all about telling the caller what the default is, so that the compiler can bake it in. My suggestion would be for the caller to effectively only say “Here’s a value” or “please use the default.”

Comments are closed.