开发者

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

开发者 https://www.devze.com 2023-01-10 06:51 出处:网络
Here\'s my method: public void SomeQuery(string email = \"\", Guid userId = Guid.Empty) { // do some query

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)
{开发者_如何学JAVA
   // do some query
}

still no love.

What am i missing?


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消