I was looking at the question Use ‘dynamic’ throw a RuntimeBinderException. I face a similar problem:
Basically, I want to create a “HTML helper” in ASP.NET MVC that uses dynamic arguments, akin to the htmlArguments parameter for many of the existing helpers (more code below):
public BootstrapCell(Action<string> emitContentAction, dynamic args)
View:
@using (grid.Cell(ViewContext.Writer.Write, new {Position = 4}))
{
<p>zomg!</p>
}
However in the naive approach, i get RuntimeBinderException thrown at me, declaring that 'object' does not contain a definition for 'Position', even though when debugging and hovering over the _args variable, it clearly does have a Position property.
The caller and the callee are in separate assemblies. Why is that problem happening?
(The solution to that has been shown in the same question: Manually create an ExpandoObject to hold the args.)
Implementation:
public class Cell
{
private readonly string _tagName;
private dynamic _args;
private Action<string> EmitContentAction;
public BootstrapCell(Action<string> emitContentAction, dynamic args) : DisposableBaseClass
{
_args = args;
EmitContentAction = emitContentAction;
OnContextEnter();
}
protected void OnContextEnter()
{
var sb = new StringBuilder("<");
sb.Append(_tagName);
if (_args.Position > 0)
{
sb.Append(" class=\"offset");
sb.Append(args.Position);
sb.Append("\"");
}
sb.Append(">");
EmitContentAction(sb.ToString());
}
}
[Edited to make clearer that my problem arises when “obviously” the Position property is set. I am aware that if the property never was defined in the first place, an exception must be raised.]
That code is fatally flawed.
It does work, as long as you specify that property:
That will output
0, it will not throw aRuntimeBinderException.But the purpose of such code is the possibility for the caller to specify only the properties needed and omit the rest.
You are trying to check for this omission via
if(args.Position != null). But that doesn’t work, it already requiresPositionto exist.When you have a look at the routing API of ASP.NET that also supports those anonymous configuration objects you will notice that the type of the parameter is
objectand notdynamic.Using
objectinstead ofdynamicwill enable your API to be used across assembly boundaries.So how does it work?
Just like in the linked answer, you need to manually create a dictionary of the properties. Whether you use a plain old
Dictionary<string, object>or anExpandoObjectis a matter of preference.Using
ExpandoObjectwill make your code a bit simpler to read and write, but it is not required.About the actual exception you are getting:
Please note that it tells you it can’t find the
Positionproperty onobject. If it would be an anonymous type that was missing thePositionproperty the exception message wouldn’t refer toobjectbut to an anonymous type. Something like this: