What is the use of speaker return in C #

... compared to simply returning an object. The magic starts when you assign an object to a dynamic declared variable, so what returns a dynamic change?

What's the difference between:

static object CreateMagicList() { return new List<string>(); } 

and

 static dynamic CreateMagicList() { return new List<string>(); } 

Both of them work the same way, for example:

 dynamic list = CreateMagicList(); list.Add( "lolcat" ); 

Please note that this is not a practical question. I'm interested in the reason :)

+4
source share
3 answers

My best guess is that you are allowed to return dynamic so you can do this:

 private static dynamic Get() { return new {X=5}; } public static void Main() { var v = Get(); Console.WriteLine(vX); } 

If you could only declare Get as object Get() , then your callers would be forced to replace var with dynamic : otherwise the code would not compile.

The same applies to the use case without var :

 public static void Main() { Console.WriteLine(Get().X); } 

without a dynamic return type, you will need to perform an intermediate assignment or use a cast in dynamic .

+2
source

I think that for understanding the specific situation in your example this may not matter much, but it is important to consider that the dynamic creator is created at runtime, so you do not need something to be disabled, just getting a return form, for example, what to do if instead you needed to not be attached to the dynamic, but to list

 static dynamic CreateMagicList() { return new List<string>(); } List<string> list = CreateMagicList(); list.Add( "lolcat" ); 

this will work just fine since at runtime you are bound to the same property

but this one

 static object CreateMagicList() { return new List<string>(); } List<string> list = CreateMagicList(); list.Add( "lolcat" ); 

will give you an error message, since you need to delete it

+1
source

You can return the dynamics so that in the future you can actually return the dynamics. With MissingMethodInvoke and MissingPropertyInvoke are overloaded. Dynamics is more than just objects.

0
source

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


All Articles