views:

187

answers:

2

Hi Guys,

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?

+1  A: 

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.

sgriffinusa
The whole point of C# 4 Optional Parameters is to avoid unecessary overloading.I have around 7 parameters that i'm filtering by (in a LINQ query), why overload a method 7 times with the same code? I guess that's the 'other constraints' your referring to. =)
RPM1984
for 2 arguments is better to have 2 overloaded methods than optional parametrs IMO. Mainly it is for design like mySuperObject.Add( ref one, ref two, ref three, ref four, ref five) vs mySuperObject.Add();
lukas
+2  A: 

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.

Quintin Robinson
That's it. Cheers!
RPM1984
@RPM1984 Glad to hear it!
Quintin Robinson
The good thing about this approach is that you can still test for it using Guid.Empty in your code. e.g.if(userId == Guid.Empty) { ... }
Bennor McCarthy
@Bennor - i was juuuuust about to write some unit tests for that exact scenario. Thanks for saving me some time! =)
RPM1984