Make checking properties on ExpandoObject or dynamic variables easier #8178
Replies: 5 comments 26 replies
-
If you want to configure checking rules on dynamic objects, just make an object derive from Example (Just an example, I don't use using System;
using System.Dynamic;
dynamic d = new ResourceDictionary("ResourceFile");
Console.WriteLine((string)d.Name); // "real value"
Console.WriteLine((string)d.UnknownPropertyName); // "default value"
class ResourceDictionary(string _resourceDictionaryName) : DynamicObject
{
public override bool TryGetMember(GetMemberBinder binder, out object? result)
{
if (binder.Name == "Name")
{
result = "real value";
return true;
}
result = "default value";
return true; // false is for failure on binding properties.
}
} |
Beta Was this translation helpful? Give feedback.
-
@SunnieShine, that's exactly why I said easier. We do have a lot of code in place. A lot of extension methods to work with
But I don't want to repeat that Your answer is not easy. This is easy:
|
Beta Was this translation helpful? Give feedback.
-
@SunnieShine, I think working with dynamic variables should become as easy as JavaScript. Because that's what it is. It's not strongly typed. We choose it for simplicity. We lose all benefits of strong typing, for the sake of simplicity. But it's syntax is not easy yet. This is what I think we can consider easy:
This can be considered easy syntax. |
Beta Was this translation helpful? Give feedback.
-
Not that it matters much anymore, but dynamic/DLR wasn't really added to make C# a dynamic language, it was added to make it easier to bridge C# with other dynamic languages hosted on the .NET runtime. At this point there isn't really any investment in this space anymore, and the binder provided by C# hasn't been keeping up with other language capabilities. I don't think there is any interest in making C# feel like Javascript. |
Beta Was this translation helpful? Give feedback.
-
The statement "complex systems are only possible with dynamic programming" is exactly the opposite of the truth. Static compilation reduces the number of bugs by orders of magnitude, and together with everything C# had to offer, like analyzers and tools, and following best practices, allows the creation of high quality code of any complexity. My advice would be to engage the services of a consultant to assess the situation in detail and create a road map to eliminate dynamic code from your product line. I may be available ;) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Consider this code:
It throws this exception:
So, this means that when we want to access a dynamic variable's property, we should first check for its existence.
That check is hard. Make it easier. Something like:
or
or
Beta Was this translation helpful? Give feedback.
All reactions