Home > Software engineering >  What is the Type of var in this case?
What is the Type of var in this case?

Time:03-14

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?

Thank you!

CodePudding user response:

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;
}

CodePudding user response:

In your current code you are trying to return anonymous type:

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

you can turn it into named tuple with a little change:

public static IEnumerable<(PropertyInfo p, 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 (p, attr.First() as T);

    return properties;
}
  • Related