Dynamic does not consider return type

I am new to the C # dynamic keyword. In one of my projects, I tried to play with him and came across some unexpected behavior. I was able to reproduce the situation with the following code:

 class Program { static DateTime? DateOnly(DateTime? time) { return time.HasValue ? (System.DateTime?)time.Value.Date : null; } static void Main(string[] args) { dynamic now = System.DateTime.Now; var date = DateOnly(now); Console.WriteLine(date.Value); // error thrown here Console.Read(); } } 

I get a RuntimeBinderException message

'System.DateTime' does not contain a definition for 'Value'.

So, is the date variable treated as DateTime instead of DateTime? .

It seems like dynamic somehow ignoring the declaration of return type. Should I avoid using var with dynamic ?

+5
source share
3 answers

As you pass the dynamic variable to the DateOnly method, the return type also becomes dynamic. So, in this case, your var date is actually a dynamic date . It contains a box with a DateTime value of zero, but the box does not save the "nullable" part, so in fact it is just a DateTime box that does not have the Value property. Therefore, you should just do Console.WriteLine(date) to print the value.

As you can see, nullable and dynamic types don't mix very well together ...

+5
source

There are two questions. One of them is that date is still dynamic, since the right side is a dynamic expression. Should you declare date specific DateTime? type DateTime? You wouldn’t see it. Another problem is that you are returning a NULL value type, and conversion to dynamic is considered boxing. Invalid value types are never placed as such. The type of the base value is expanded, so does date behave more like a reference of type object , which can either have a DateTime, or it can be null, and not a reference to DateTime? . The binder then tries to resolve the Value property compared to DateTime and fails. If you try Console.WriteLine(date) , however it will not be so straightforward because this method has so many overloads. So you will need to do something like Console.WriteLine((object)date) , after which you can declare date as object for this simple example.

+2
source

look at your function parameter, you are requesting a type with a null value. DateTime (System.DateTime.Now) - value type and default value types are not NULL.

0
source

Source: https://habr.com/ru/post/1240489/


All Articles