Should I use a Guid and Guid.Empty or a nullable Guid?

indra picture indra · Jul 18, 2013 · Viewed 17.3k times · Source

I have certain scenarios (e.g. a custom class to hold Sql parameters) in which a variable may or may not be required. Traditionally I have always defined these being of type Guid? and used myGuid.HasValue to check for a valid value before using.

Of course in practice I could also use regular Guids and perform the check for valid value with myGuid == Guid.Empty.

For readability I prefer the first usage as it feels cleaner but I would appreciate it if someone could advise on whether one of these methods is better (faster, quicker or more correct) than the other?

Answer

Eren Ersönmez picture Eren Ersönmez · Jul 18, 2013

If the parameter can be null on the T-Sql side, then I think Guid? is a more natural fit. Especially when used with ADO.NET parameterized queries, nullable types are conveniently translated to DBNull.Value when their value is null. If you were to use Guid.Empty to indicate null, then you'd need to check for that condition and explicitly pass DBNull.Value to your command/query. E.g.:

command.Parameters.AddWithValue("@guid", myNullableGuid)     

vs.

command.Parameters.AddWithValue("@guid", 
    myGuid == Guid.Empty ? DBNull.Value : myGuid)    

There is virtually no performance difference between the two alternatives, otherwise.