Question

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?

Était-ce utile?

La solution

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.

Autres conseils

I think that approach with Guid? is much more better. It just a coincidence that a default value of Guid whuch is equal to Guid.Empty has no real usage and can be treated as null value. For example, int or bool default values are used without any distinction with other values. So, IMHO, you should use Guid? to stay consistent.

I usually use declaring like the followings:

Guid? objGuidStudent = null;
objGuidStudent = Students.FindByName('Oscar');
Classrooms.Add(x, y, z, objGuidStudent);

It works perfectly, either with or without NULL value.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top