Test If a Property Is Available on a Dynamic Variable

Test if a property is available on a dynamic variable

I think there is no way to find out whether a dynamic variable has a certain member without trying to access it, unless you re-implemented the way dynamic binding is handled in the C# compiler. Which would probably include a lot of guessing, because it is implementation-defined, according to the C# specification.

So you should actually try to access the member and catch an exception, if it fails:

dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();

try
{
var x = myVariable.MyProperty;
// do stuff with x
}
catch (RuntimeBinderException)
{
// MyProperty doesn't exist
}

How do I check if a property exists on a dynamic anonymous type in c#?

  public static bool DoesPropertyExist(dynamic settings, string name)
{
if (settings is ExpandoObject)
return ((IDictionary<string, object>)settings).ContainsKey(name);

return settings.GetType().GetProperty(name) != null;
}

var settings = new {Filename = @"c:\temp\q.txt"};
Console.WriteLine(DoesPropertyExist(settings, "Filename"));
Console.WriteLine(DoesPropertyExist(settings, "Size"));

Output:

 True
False

How to test if a property has been declared as dynamic?

If you put your code in SharpLib.io, you can see what happens to your code behind the scenes.

using System;
public class C {
public dynamic SomeProp { get; set; }
public void M() {
SomeProp = 3;
}
}

is converted to (removed some stuff for readability):

using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;

public class C
{
[Dynamic]
private object <SomeProp>k__BackingField;

[Dynamic]
public object SomeProp
{
[return: Dynamic]
get
{
return <SomeProp>k__BackingField;
}
[param: Dynamic]
set
{
<SomeProp>k__BackingField = value;
}
}

public void M()
{
SomeProp = 3;
}
}

The SomeProp property is just a plain object for the .Net runtime. With a [Dynamic] attribute attached.

There is no way to test for the dynamic type, since it is not the type of SomeProp. You should test for the presence of the [Dynamic] attribute.

How to safely check if a dynamic object has a field or not

You need to surround your dynamic variable with a try catch, nothing else is the better way in makking it safe.

try
{
dynamic testData = ReturnDynamic();
var name = testData.Name;
// do more stuff
}
catch (RuntimeBinderException)
{
// MyProperty doesn't exist
}

Dynamic Object - How to tell if a property is defined?

bool isDefined = false;
object axis = null;
try
{
axis = this.ChartDetails.Chart.LeftYAxis;
isDefined = true;
}
catch(RuntimeBinderException)
{ }

This is what happens at runtime in the first place. (When you access a property the 'dynamic' piece of things only happens when a first-chance exception gets handled by the object's override of DynamicObject's TryGetMember and TrySetMember

Some objects (like ExpandoObject) are actually dictionaries under the hood and you can check them directly as follows:

bool isDefined = ((IDictionary<string, object>)this.ChartDetails.Chart)
.ContainsKey("LeftYAxis");

Basically: without knowing what actual type ChartDetails.Chart is (if it's an ExpandoObject a plain ol' subclass of object or a subclass of DynamicObject) there's no way besides the try/catch above. If you wrote the code for ChartDetails and Chart or have access to the source code you can determine what methods exist for the object and use those to check.

How to dynamically check if a property exists in an object?

You're not properly optional chaining your errors?.logic[conditionIndex]?.scenarios[scenarioIndex]?.operator bit.

If you want to optional chain with a [key] access, use ?.[key], e.g. errors?.logic?.[conditionIndex]?.scenarios?.[scenarioIndex]?.operator.

Is there a way to test if a variable is dynamic?

Firstly, you need to separate the variable and the object. A variable is dynamic if it is defined as dynamic. That is all. There is nothing more. A field or property would be annotated with the [Dynamic] attribute, i.e.

public dynamic Foo {get;set;}

is actually:

[Dynamic]
public object Foo {get;set;}

This basically acts as a prompt for the compiler to access the object via the dynamic API rather than via the OOP API.

An object supports full dynamic capabilities if it implements IDynamicMetaObjectProvider - however, such an object can be accessed via both the dynamic API and via the regular OOP API (it can have both). Equally, an object that doesn't implement IDynamicMetaObjectProvider can be accessed via either API (but: only the public members will be available via dynamic).

Dynamically access object property using variable

There are two ways to access properties of an object:

  • Dot notation: something.bar
  • Bracket notation: something['bar']

The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:

var something = {
bar: 'foo'
};
var foo = 'bar';

// both x = something[foo] and something[foo] = x work as expected
console.log(something[foo]);
console.log(something.bar)


Related Topics



Leave a reply



Submit