0

Why the c# compiler are not capable to accept:

string propValue = "2017/12/01";
object propObjValue = null;
DateTime.TryParse(propValue, out propObjValue);

Compiler error: Argument 2: cannot convert from 'out object' to 'out System.DateTime'

However it do accept:

string propValue = "2017/12/01";
object propObjValue = null;
propObjValue = DateTime.Parse(propValue);

Which is equivalent, except in the second approach I need to do try/catch to avoid parsing issues.

Israel Garcia
  • 778
  • 7
  • 16
  • `DateTime` is an `object`, but an `object` is not a `DateTime`. – Sach Aug 25 '17 at 18:06
  • You're calling two completely different methods. There's no requirement that different methods "act similarly" just because of similar names – Damien_The_Unbeliever Aug 25 '17 at 18:07
  • If you read the [`DateTime` info on MSDN](https://learn.microsoft.com/en-us/dotnet/api/system.datetime?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DEN-US%26k%3Dk(System.DateTime);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5.2);k(DevLang-csharp)%26rd%3Dtrue&view=netframework-4.7), you'd understand. The inheritance hierarchy is `Object -> ValueType -> DateTime`. – Sach Aug 25 '17 at 18:10
  • Shame it closed. I was writing an answer about how `out` is a lie and only `ref` really exists, and so how you have to accept that the called method can call specific methods on the passed in variable, after avoiding `null`s. I'm not sure I see that in the linked Q – Damien_The_Unbeliever Aug 25 '17 at 18:17
  • @Damien_The_Unbeliever The linked question specifically covers the variable being modified from outside the scope of the method as the reason that this doesn't work, so that's already there. – Servy Aug 25 '17 at 18:22
  • Yes, I just realized is already covered by the referenced question, the problem is that "out" can modify the object parameter inside the function, not only assigning a value. So if I pass a more general object they are not allowed to modify DateTime. – Israel Garcia Aug 25 '17 at 18:29

0 Answers0