-3

Considering that value types are always initalised by default and never null would it be worth to null check value types passed in to methods via parameters?

E.g. is it worth performing the following check

public void Method(Guid x)
{
  if (x == null)
   throw new ArgumentNullException();
...
}
TheAkhemist
  • 219
  • 1
  • 14
  • 4
    You can't compare value types to null. You'll get a compiler error. What you can do instead is compare it to `default(Guid)`. It's a similar check, but `default(type)` is usually a valid value as well (e.g. `default(int)` is 0), so you need to be careful. – itsme86 Jul 29 '16 at 15:19
  • 2
    What's the point of null-checking something that can never be null? Is there some other question behind this one? – Panagiotis Kanavos Jul 29 '16 at 15:20
  • @Venky it's *already* a Guid, what is there to validate? `Parse` and `TryParse` are used to convert *strings* to Guids – Panagiotis Kanavos Jul 29 '16 at 15:21
  • 1
    @itsme86: Interestingly, for `Guid`s anyway, you don't get a compiler error. – sstan Jul 29 '16 at 15:36
  • 2
    @sstan See this question for an explanation: http://stackoverflow.com/questions/2177850/guid-null-should-not-be-allowed-by-the-compiler – itsme86 Jul 29 '16 at 15:45
  • 1
    @itsme86, this will compile just fine. Hopefully the compiler is smart enough to toss the code in release mode but their is nothing wrong with checking is a guid is equal to null. (it will always be false) – Matthew Whited Jul 29 '16 at 16:00

1 Answers1

1

Though the condition is technically valid (because of operator overload rules and nullable types), it can only ever evaluate to false. That's why, in some cases, you will get a compiler warning to let you know that the only possible outcome is false.

So, unless there is more to your question, it comes down to asking if this code is worth it:

public void Method(Guid x)
{
  if (false)
   throw new ArgumentNullException();
...
}

The answer should be pretty obvious.

sstan
  • 35,425
  • 6
  • 48
  • 66