I have code a bit like this
public class MyObject
{
private bool IsValidDay(ref DateTime theDate)
{
...
}
}
MethodInfo[] methods = myObjectInstance.GetType().GetMethod("IsValidDay", BindingFlags.Instance | BindingFlags.NonPublic);
object[] args = { null };
bool val = (bool)method.Invoke(myObjectInstance, args);
But when the method is called, from within the IsValidDay method, theDate is DateTime.MinValue. This seems awfully weird - I'd perhaps expect a NullReferenceException to be thrown but not an automatic conversion.
In case you are wondering, this is code in a unit test. (in use the method is typically called via a public method that takes object).
As far as some other code which is subsequently called is concerned, DateTime.MinValue and null are not the same thing, so it's a little bit of a problem.
Any clues?? Suggestions.
From MSDN:
Any object in this array that is not explicitly initialized with a value will contain the default value for that object type. For reference-type elements, this value is null. For value-type elements, this value is 0, 0.0, or false, depending on the specific element type.
The default value of DateTime
is DateTime.MinValue
:
DateTime.MinValue == new DateTime() // true
This explains why DateTime.MinValue
gets passed to the method when you call it with null
.
Note that you cannot pass null
to the method anyway when you call it without reflection:
DateTime dt = null; // cannot assign null to value type
obj.IsValidDay(ref dt);
So I'd say you don't need to test your method with a null reference.
If you want your method to accept null
, you can change the declaration to DateTime?
as others have already pointed out:
private bool IsValidDay(ref DateTime? dt) { ... }
A DateTime variable can't be null. It's not a reference type, so there won't be a null reference exception.
You could do:
private bool IsValidDay(ref DateTime? theDate)
{
if(theDate.HasValue)...
}
Here's a link talking about nullable types: http://msdn.microsoft.com/en-us/library/1t3y8s4s%28VS.80%29.aspx
I think I get what you are asking.... in the case of your code (especially because of the ref parameter, you can't have variance on a parameter with ref or out). It has to pass in a DateTime object. It can't be anything else.....so the null argument has to be converted to something to get the function to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With