Note that there are some explanatory texts on larger screens.

plurals
  1. POCast a property to its actual type dynamically using reflection
    primarykey
    data
    text
    <p>I need to cast a property to its actual type dynamically. How do I/Can I do this using reflection?</p> <p>To explain the real scenario that I am working on a bit. I am trying to call the "First" extension method on an Entity Framework property. The specific property to be called on the Framework context object is passed as a string to the method (as well as the id of the record to be retrieved). So I need the actual type of the object in order to call the First method. </p> <p>I can't use the "Where" method on the object as the lambda or delegate method still needs the actual type of the object in order to access the properties.</p> <p>Also as the object is generated by the Entity Framework I can't cast the type to an interface and operate on that.</p> <p>This is scenario code:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Reflection; namespace NmSpc { public class ClassA { public int IntProperty { get; set; } } public class ClassB { public ClassA MyProperty { get; set; } } public class ClassC { static void Main(string[] args) { ClassB tester = new ClassB(); PropertyInfo propInfo = typeof(ClassB).GetProperty("MyProperty"); //get a type unsafe reference to ClassB`s property Object property = propInfo.GetValue(tester, null); //get the type safe reference to the property ClassA typeSafeProperty = property as ClassA; //I need to cast the property to its actual type dynamically. How do I/Can I do this using reflection? //I will not know that "property" is of ClassA apart from at runtime } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload