Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the Type of var in this case?

I stumbled upon this post https://stackoverflow.com/a/5249859/13174465 about reflection in C#. My idea is to create a helper method out of it to use it in multiple places across my code. But I can’t figure out what return type the method should have.
The IDE shows the type local variable IEnumerable<{PropertyInfo Property, T Attribute}> properties but this isn’t accepted as return type of a method.

This is my current code which obviously doesn’t work.

public static IEnumerable<PropertyInfo, T> GetPropertiesAndAttributes<T>(object _instance, BindingFlags _bindingFlags = FULL_BINDING) where T : Attribute
    {
        var properties = from p in _instance.GetType().GetProperties(_bindingFlags)
            let attr = p.GetCustomAttributes(typeof(T), true)
            where attr.Length == 1
            select new { Property = p, Attribute = attr.First() as T};

        return properties;
    }

Which return type would be correct to make this method functional?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you!

>Solution :

This creates an anonymous object:

new { Property = p, Attribute = attr.First() as T }

Anonymous types are generated by the compiler, so you can’t declare a method that returns an anonymous type; they can exist in local scope only.

If you want to return the enumeration, you could use a ValueTuple as the item type instead:

public static IEnumerable<(PropertyInfo Property, T Attribute)> GetPropertiesAndAttributes<T>(
    object _instance, BindingFlags _bindingFlags = FULL_BINDING)
where T : Attribute
{
    var properties = from p in _instance.GetType().GetProperties(_bindingFlags)
        let attr = p.GetCustomAttributes(typeof(T), true)
        where attr.Length == 1
        select (Property: p, Attribute: attr.First() as T);

    return properties;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading