How to set null value to the Guid property in c#

By | November 5, 2017

How to set a null value to the Guid Property in C#.Net

One of my friend was working on a project, and he want is to assign a null / Empty / default parameter to guid property in and what he was trying as below, so lets see How to set null value to the Guid property

public void SampleFunction(Guid guidParameter = Guid.Empty)

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


What we can use is,

public void SampleFunction(Guid guidParameter = new Guid()){
  // when called without parameters this will be true
  var guidIsEmpty = guidParameter == Guid.Empty;}

When we call above method, without any paramter, then it will assign “Empty” Value to the guidParameter, so in that case “guidIsEmpty” will be true.

We can also use default(Guid) instead of “new Guid()”, it will work same.

Why didn’t Guid.Empty work?

The reason we 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).


Guid.Empty is equivalent to new Guid(), which is equivalent to default(Guid).
So you can use:
Assign Guid.Empty value to Guid

public void SampleFunction(Guid guidParameter = default(Guid))


public void SampleFunction(Guid guidParameter = new Guid())


public void SampleFunction(Guid? guidParameter = null)