List<MyClass> MyClassPro
{
get;set;
}
MyClass obj = new MyClass();
obj.MyClassPro = null;
Consider the MyClassPro is null. In situation of Reflection i wont be knowing the Classname or Property Name.
If i try to get the Type of property using GetType like ,
Type t = obj.GetType();
It is returning "System.Collections.Generic.list. But my expectation is to get the Type as MyClass.
I also tried the way like
foreach(PropertyInfo propertyInfo in obj.GetProperties())
{
if(propertyInfo.IsGenericType)
{
Type t = propertyInfo.GetValue(obj,null).GetType().GetGenericArguments().First();
}
}
But it is returning error because of the Value of the collection property is null so we cant get the Type.
In this situation how can i get the Type of a collection Property.
Please help me !
Thanks in Advance.
Finally, if we can't find that, we look for ICollection, and look for an Add () method with a single parameter that is not of type object. I've found this to be the most reliable way to determine the element type of a collection. Finally if that doesn't work, we look for IEnumerable and if we find it, we return the object type.
System. Reflection System. Reflection Discovers the attributes of a property and provides access to property metadata. Microsoft. JScript. COMProperty Info System. Reflection. Emit. Property Builder This example shows how to use various reflection classes to analyze the metadata contained in an assembly.
To determine the type of a particular property, do the following: Get a Type object that represents the type (the class or structure) that contains the property. Get a PropertyInfo object that represents the property in which you're interested. Retrieve the value of the PropertyType property from the PropertyInfo object.
These collections are surprisingly common. For example, much of Windows Forms as well as the CodeDOM have typed collections like this. Getting the element type is far more involved for these collections.
Use propertyInfo.PropertyType
instead of propertyInfo.GetValue(obj,null).GetType()
which should give you the property type even if the property value is null
.
So when you have a class like
public class Foo {
public List<string> MyProperty { get; set; }
}
and an instance of Foo
in obj
, then
var propertyInfo = obj.GetType().GetProperty("MyProperty"); // or find it in a loop like in your own example
var typeArg = propertyInfo.PropertyType.GetGenericArguments()[0];
will give you the value System.String
(as a System.Type
instance) in typeArg
.
Use propertyInfo.PropertyType
which has property with name IsGenericType
, e.g.:
if (propertyInfo.PropertyType.IsGenericType)
{
// code ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With