1

I have type references A and B but I want the name of the ICollection<A> which is a property of B. How can I get the collection name "BunchOfX" if I only have the two types?

public class X
{
}

public class Y
{
   public virtual ICollection<X> BunchOfX { get; set; }
}

I need something that can give me the property name "BunchOfX" when all I have is the type references A and B. Let's say A will reference the type that the ICollection<> holds, and B will reference the type the ICollection<> is defined on.

The Real Code

var entityType = Type.GetType(nameSpace + "." + entityTypeName);
var foreignType = Type.GetType(nameSpace + "." + foreignTypeName);
var names = foreignType.GetProperties()
    .Where(p => typeof(ICollection<entityType>).IsAssignableFrom(p.PropertyType))
    .Select(p => p.Name);
var foreignCollectionName = names.FirstOrDefault();

entityType gives "type or namespace unknown" when it is in the <>

Solution based on Jon and Ani's replies

var foreignCollectionName = foreignType.GetProperties()
    .Where(p => typeof(ICollection<>)
        .MakeGenericType(entityType)
        .IsAssignableFrom(p.PropertyType))
    .Select(p => p.Name).FirstOrDefault();
Anujith
  • 9,370
  • 6
  • 33
  • 48
Benjamin
  • 3,134
  • 6
  • 36
  • 57
  • You'll most likely have to do it through reflection, or are you asking for specific code to find it? – Roman Sep 04 '11 at 17:17
  • Are you saying that you want to call `Method(b.BunchOfA)` and be able to have `Method` know that it was passed in a property called `BunchOfA`? – Gabe Sep 04 '11 at 17:17
  • @R0MANARMY I figured reflection, but I am a total beginner with .NET - specific code would be ideal. If it is very complicated then being pointed in the right direction would also be helpful. Thanks for your reply! – Benjamin Sep 04 '11 at 17:19
  • possible duplicate of [workarounds for nameof() operator in C#: typesafe databinding](http://stackoverflow.com/questions/301809/workarounds-for-nameof-operator-in-c-typesafe-databinding) – Gabe Sep 04 '11 at 17:19
  • @Gabe I'm not sure what you mean. But I think I asked the question the wrong way so I edited it. Thanks for your reply! – Benjamin Sep 04 '11 at 18:05

1 Answers1

4

You'd need to look through the properties with reflection. The easiest way to do this is using LINQ:

var names = typeOfB.GetProperties()
                   .Where(p => p.PropertyType == typeof(desiredPropertyType))
                   .Select(p => p.Name);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194