Ian Ringrose Ian Ringrose - 8 months ago 160
C# Question

How can I default a parameter to Guid.Empty in C#?

I wish to say:

public void Problem(Guid optional = Guid.Empty)

But the compiler complains that Guid.Empty is not a compile time constant.

As I don’t wish to change the API I can’t use:



Make it new Guid() instead.

public void Problem(Guid optional = new Guid())
  // when called without parameters this will be true
  var guidIsEmpty = optional == Guid.Empty;

Alternative solution:

default(Guid) also will work exactly as new Guid().

Because Guid is a value type not reference type, so, default(Guid) is not equal to null for example, instead, it's equal to calling default constructor.

Which means that this:

public void Problem(Guid optional = default(Guid))
  // when called without parameters this will be true
  var guidIsEmpty = optional == Guid.Empty;

It's exactly the same as the original example.

Root Cause:

The reason you are getting the error is because Empty is defined as:

public static readonly Guid Empty;

So, it is a variable, not a constant (defined as static readonly not as const). Compiler can only have compiler-known values as method parameters default values (not runtime-only-known).

The root cause is that you cannot have a const of any struct, unlike enum for example. If you try it, it will not compile.

The reason once more is that struct is not a primitive type.
For a list of all primitive types in .NET see http://msdn.microsoft.com/en-gb/library/system.typecode.aspx
(note that enum usually inherits int, which is a primitive)


I'm not saying it needs a constant. It needs something that can be decided in compile time. Empty is a field, so, it's value is not known in compile time (only at very beginning of run time).

Default parameter value must be known at compile-time, which may be a const value, or something defined using a C# feature that makes value known at compile time, like default(Guid) or new Guid() (which is decided at compile time for structs as you cannot modify the struct constructor in code).

While you can provide default or new easily, you cannot provide a const (because it's not a primitive type or an enum as explained above). So, again, not saying that optional parameter itself needs a constant, but compiler known value.