-1
CreatedDate = meta.CreatedDate.HasValue ? meta.CreatedDate.Value.ToShortDateString : null

This line of code throws exception 'Type of conditional expression cannot be determined because there is no implicit conversion between method group and null.'

Is there any working way to make this check and and/or any more elegant (less ugly) way?

Note:

myObject = (dynamic)new
{
    CreatedDate = meta.CreatedDate.HasValue ? meta.CreatedDate.Value.ToShortDateString : null
}
  • 1
    `meta.CreatedDate.Value.ToShortDateString` is a method group. `meta.CreatedDate.Value.ToShortDateString()` is how to call the method. – Enigmativity Apr 10 '18 at 12:55
  • Possible duplicate of [What does question mark and dot operator ?. mean in C# 6.0?](https://stackoverflow.com/questions/28352072/what-does-question-mark-and-dot-operator-mean-in-c-sharp-6-0) – SᴇM Apr 10 '18 at 13:03
  • 1
    @SeM - No, it's not. The issue here is that the OP missed putting the `()` at the end of his method call. He's not asking about the dot operator at all. – Enigmativity Apr 10 '18 at 13:05
  • 1
    The code doesn't throw an exception - it doesn't compile and hence can't throw an exception. – Enigmativity Apr 10 '18 at 13:06
  • @Enigmativity it's for "more elegant way to check for null" – SᴇM Apr 10 '18 at 13:06
  • @SeM - Yes, it is, but that not asking what the `?.` operator does. It's a different question, but around the same topic. – Enigmativity Apr 10 '18 at 13:13
  • Ops, yes i forget the braces, thanks y'all. Any more elegant way anyway :) ?? – Ceylan Mumun Kocabaş Apr 10 '18 at 13:55
  • Thank you all. And probably i've learned my lesson again (for 1000th time) - if you sleepy and exhausted - coffee brake :) – Ceylan Mumun Kocabaş Apr 10 '18 at 14:14

2 Answers2

4

You are missing the calling braces () for method call it should be ToShortDateString() as for calling a method we need those so, your code line should look like:

CreatedDate = meta.CreatedDate.HasValue ? meta.CreatedDate.ToShortDateString() : null ;

But If you are using C# 6 you can do following via null propagation operator:

String CreatedDate = meta.CreatedDate?.ToShortDateString();

or:

String CreatedDate = meta.CreatedDate?.Value.ToShortDateString();

and if you are below C# 6 then try :

String CreatedDate = meta.CreatedDate.HasValue ? meta.CreatedDate..ToShortDateString() ? null;
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
2

You can use the null-conditional operator:

CreatedDate = meta.CreatedDate?.ToShortDateString();
Peter M.
  • 1,240
  • 2
  • 9
  • 25
  • 1
    You should fix your code: `.ToShortDateString` is a method group. `.ToShortDateString()` is how to call a method. – Enigmativity Apr 10 '18 at 12:56