C# 4.0 Optional Parameters - How to Specify Optional Parameter of Type "Guid"?

Here's my method:

public void SomeQuery(string email = "", Guid userId = Guid.Empty)
{
   // do some query
}

userId is giving me an error as it must be a compile-time constant, which i understand. But even when i declare a const:

private const emptyGuid = Guid.Empty;

then change the method signature to:

public void SomeQuery(string email = "", Guid userId = emptyGuid)
{
   // do some query
}

still no love.

What am i missing?

Answers


Have you tried setting it to a new instance of Guid ala:

public void SomeQuery(string email = "", Guid userId = new Guid())
{
   // do some query
}

Should do the trick.


Wouldn't a better solution be to overload the method with a version that doesn't require the Guid? This would solve the issue, and would be a better design in my opinion. Of course, there may be other constraints that I am unaware of necessitating this design.


maybe it would help (using operator ?? and Guid nullable type)

public void some_method(string name, Guid? guid = null)
{
        _name = name;
        _guid = guid ?? Guid.NewGuid();
}

Need Your Help

SQL Server 2008 Empty String vs. Space

sql-server sql-server-2008 tsql string-length datalength

I ran into something a little odd this morning and thought I'd submit it for commentary.

How are decorators (annotations) compiled in Typescript?

typescript angular

In Angular 2, I can create a component, like this: