The blog has moved to the new site F10Debug.com

Monday, September 25, 2017

How to assign default or null or empty parameter to Guid

One of my friend working on one project, and he wants to assign the null / Empty / default parameter to guid,

public void SampleFunction(Guid guidParameter = Guid.Empty)
{
}
But the compiler complains that Guid.Empty is not a compile time constant.
Solution 
We can use,
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 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).
Note:
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))
or
public void SampleFunction(Guid guidParameter = new Guid())
Assign Null value to Guid 
public void SampleFunction(Guid? guidParameter = null)



No comments:

Post a Comment