SamJolly
SamJolly

Reputation: 6477

How to find the type of a property, particularly between simple and collection types?

I am using MVC3, C#, Razor, .NET4, EF5, SQL Server 2008.

I need to find out what the types of a property is on a domain object, particularly whether it is a ICollection ie Navigation Property or a simple POCO type ie int, string etc.

Basically I am mapping from a View to a Domain object, and I need to exclude the navigation properties (ICollection). I am using Value Injector and I can write a custom injector to ignore ICollection.

There is the "TypeOf" function I believe.

So my pseudo logic would be along the lines of:

Match if not(typeOf(ICollection))

Many thanks.

EDIT:

Tried first solution, but could not get it to work. Sample code below. All return true. I would expect isCollection1 and 2 to be false and 3 and 4 to be true.

Thoughts?

        bool isCollection2 = stdorg.Id is System.Collections.IEnumerable;
        bool isCollection3 = stdorg.StdLibraryItems is System.Collections.IEnumerable;

EDIT2:

This works for me:

bool IsCollection = (stdorg.StdLibraryItems.GetType().Name == "EntityCollection`1")

Value Injector actually required me to use:

bool IsCollection = (stdorg.StdLibraryItems.GetType().Name == "ICollection`1")

and this works a treat. For those interested Value Injector has a matching routine, and putting this condition in determines whether the match returns true, and if it does it sets the Target property value to that of the Source Property Value.

Upvotes: 0

Views: 151

Answers (2)

phil soady
phil soady

Reputation: 11338

He is a general type solution that may solve other property questions as well. Especially if something is nullable.

    foreach (var propertyInfo in typeof (T).GetProperties()) { //<< You know about typeof T already
          var propType = UnderLyingType(propInfo); 
          //if( decide if collection?){}
    }


    public Type UnderLyingType(PropertyInfo propertyInfo) {
        return Nullable.GetUnderlyingType(propertyInfo.PropertyType) 
               ?? propertyInfo.PropertyType;
    }

You may want to look at the info available in PropInfo as well.

Upvotes: 1

Varun K
Varun K

Reputation: 3638

If you have access to the property or object with the dot syntax, you can use the is operator.

var obj = new List<string>();
bool collection = obj is System.Collections.IEnumerable; // true since IEnumerable is the base interface for collections in .NET

If you are accessing properties via Reflection using methods like Type.GetMembers, you can use t.GetInterface("System.Collections.IEnumerable"). Where t is the type of that instance. The method GetInterface(string) returns null if that type does not implement the said interface.

Upvotes: 1

Related Questions