12

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?

RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • Possible duplicate of [How can I default a parameter to Guid.Empty in C#?](https://stackoverflow.com/questions/5117970/how-can-i-default-a-parameter-to-guid-empty-in-c) – Michael Freidgeim Nov 19 '17 at 11:49

3 Answers3

20

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
  • 81,193
  • 14
  • 123
  • 132
  • 3
    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 Aug 04 '10 at 00:51
  • @Bennor - i was juuuuust about to write some unit tests for that exact scenario. Thanks for saving me some time! =) – RPM1984 Aug 04 '10 at 00:52
  • 2
    You should avoid optional parameters when possible. They're a code smell. Also, they encourage bad API's by making encapsulation much harder, and by encouraging different behaviors to be implemented by the same method. – Eamon Nerbonne Nov 07 '12 at 12:23
2

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();
}
user956669
  • 21
  • 1
  • 3
  • hi, if i try this i get a message (roughly translated): A value of Type '' kann not be used as standard parameter, becuse there is no standardconversion to "System.Guid' – Offler Jan 17 '13 at 16:20
2

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
  • 4,203
  • 1
  • 25
  • 26
  • 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 Aug 04 '10 at 00:46
  • 1
    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(); – Lukasz Madon Aug 04 '10 at 01:34