Andrea
Andrea

Reputation: 894

Rationale behind constraining default parameters as compile-time constants

I am wondering why this would not compile:

public static void SomeFunction(Guid someGuid = Guid.NewGuid())
{
        // Do stuff
}

with the message

"Default parameter value for 'someGuid' must be a compile-time constant"

while the overloaded version would compile:

    public static void SomeFunction()
    {
        SomeFunction(Guid.NewGuid());
    }

    public static void SomeFunction(Guid someGuid)
    {
        // Do stuff
    }

In other words, why doesn't the compiler translate the first situation in the second? What lies behind this design choice?

Upvotes: 1

Views: 98

Answers (1)

SLaks
SLaks

Reputation: 887897

Default parameter values are compiled to CIL metadata (like attributes) which can only hold literal values.

The C# compiler does some magic there to allow decimals as well.

Upvotes: 1

Related Questions