Matthias Güntert
Matthias Güntert

Reputation: 4668

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

As the title says, when using reflection, how can I test if a property has been declared as dynamic?

Unfortunately using !pi.PropertyType.IsValueType isn't specific enough in my case. The only way I found is to look through the pi.CustomAttributes array and test if it contains an item with an AttributeType of DynamicAttribute. Is there a better way to achieve this goal?

public class SomeType
{
    public dynamic SomeProp { get; set; }
}

// ...

foreach (var pi in typeof(SomeType).GetProperties())
{
    if (pi.PropertyType == typeof(string)) { } // okay
    if (pi.PropertyType == typeof(object)) { } // okay 
    if (pi.PropertyType == typeof(dynamic)) { } // The typeof operator cannot be used on the dynamic type
}

Thanks for the replies. This is how I solved it:

public static class ReflectionExtensions
{
    public static bool IsDynamic(this PropertyInfo propertyInfo)
    {
        return propertyInfo.CustomAttributes.Any(p => p.AttributeType == typeof(DynamicAttribute));
    }
}

Upvotes: 0

Views: 76

Answers (1)

GvS
GvS

Reputation: 52528

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.

Upvotes: 2

Related Questions