1

I have the following code:

DateTime? toDate = null;
DateTime.TryParseExact(toDateTextBox.Text, "dd-MM-yyyy", null,
                       System.Globalization.DateTimeStyles.None, out toDate);

Error: cannot convert from 'out System.DateTime?' to 'out System.DateTime'

I wonder why it is not possible to pass a convert DateTime? to DateTime, in spite of it is actually a conversion from DateTime to DateTime?.

Homam
  • 23,263
  • 32
  • 111
  • 187
  • possible duplicate of [C# : Why doesn't 'ref' and 'out' support polymorphism?](http://stackoverflow.com/questions/1207144/c-why-doesnt-ref-and-out-support-polymorphism) – digEmAll Apr 04 '11 at 09:27

4 Answers4

3

An out param requires the exact same data type. What is getting passed is a reference to the variable and that reference is getting updated with the value. Since DateTime and DateTime? are actually two different types (regardless of the ability to convert between them) the call fails.

Talljoe
  • 14,593
  • 4
  • 43
  • 39
  • Why `regardless of the ability to convert between them` in `out` type and not in `in` type ? – Homam Apr 04 '11 at 08:57
  • Because the out param needs some place to store the DateTime object. It can't store it in the DateTime? variable because they aren't the same type. C# could probably do some magic under the covers to make it work, but that's probably very low on the list of priorities. – Talljoe Apr 04 '11 at 09:03
2

Because there is no implicit conversion exists between Nullable<DateTime> to DateTime. (DateTime? is actually syntactic sugar for Nullable<DateTime>).

Nullable structure's Value Property is actually has the value of the valuetype.

Sanjeevakumar Hiremath
  • 10,985
  • 3
  • 41
  • 46
1

When you use out and ref parameter the variable type must match the parameter type.

The main reason is to ensure type-safety, look at this example to have an idea:

public static void Do(out object value)
{
   value = new Foo();
} 


string myStr;
Do(out myStr); // OMG I'm setting Foo inside a string !!
digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • 1
    I've just found an Eric Lippert's [blog entry dealing with this argument](http://blogs.msdn.com/b/ericlippert/archive/2009/09/21/why-do-ref-and-out-parameters-not-allow-type-variation.aspx) and it points also to a [really good question here](http://stackoverflow.com/questions/1207144/c-why-doesnt-ref-and-out-support-polymorphism/1207302#1207302), then I will propose to close this question as duplicate :) – digEmAll Apr 04 '11 at 09:27
0

cannot convert from System.DateTime? to System.DateTime because this out parameter needs not nullable datetime type variable. but you are sending nullable datetime parameter to it.

AEMLoviji
  • 3,217
  • 9
  • 37
  • 61