1

Consider this structure:

Name
{
    public string FirstName { get; set; }
}

Person
{
    public Name PersonName { get; set; }
}

I have the name of the FirstName property as a string. Now I want to use this string "FirstName" to get the name of the Person Class at runtime. I'm not sure if this is possible. Does anyone know of a way to achieve this?

Thanks!

2
  • Not sure if I follow. You mean if you have an instance of Person such that Person.PersonName.FirstName == "Bob", that somewhere you can have a method Person FindPersonByName(string name), feed in "Bob" and it will return you the instance of the Person class in memory that was assigned "Bob" previously? Commented Jul 11, 2012 at 15:02
  • Or do you mean find the reference to all "Types" that somewhere in their property chain declare a property named "FirstName"? Something like FindTypesWithPropertyName("FirstName") and it would return both typeof(Name) and typeof(Person)? Commented Jul 11, 2012 at 15:05

2 Answers 2

2

This is a really strange requirement. That said, here's how you can do this:

// 1. Define your universe of types. 
//    If you don't know where to start, you could try all the  
//    types that have been loaded into the application domain.
var allTypes = from assembly in AppDomain.CurrentDomain.GetAssemblies()
               from type in assembly.GetTypes()
               select type;

// 2. Search through each type and find ones that have a public  
//    property named "FirstName" (In your case: the `Name` type).    
var typesWithFirstNameProp = new HashSet<Type>
(
        from type in allTypes
        where type.GetProperty("FirstName") != null
        select type
);


// 3. Search through each type and find ones that have at least one 
//    public property whose type matches one of the types found 
//    in Step 2 (In your case: the `Person` type).
var result = from type in allTypes
             let propertyTypes = type.GetProperties().Select(p => p.PropertyType)
             where typesWithFirstNameProp.Overlaps(propertyTypes)
             select type;
Sign up to request clarification or add additional context in comments.

Comments

1

If all types are in a known one or more assembly, you can search in the assembly:

var types = Assembly.GetExecutingAssembly().GetTypes();
var NameType = types.First(t => t.GetProperty("FirstName") != null);
var PersonType = types.First(t => t.GetProperties.Any(pi => pi.MemberType = NameType));

1 Comment

Good answer, but a small caution: if more than one type in the assembly has a property with that name, the type returned from types.First() may not be the one you expect. If all properties of all types have unique names, this isn't a problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.