Check T generic type has property S (generic) in c#
10,637
Solution 1
The best and easiest thing to do is implement this functionality using an interface.
public interface IHasSome
{
SomeType BArray {get;set;}
}
class C:A, IHasSome
{
public SomeType BArray {get;set;}
}
Then you can cast the object in your generic method:
public T Initial<T,S>() where T : new() where S : SomeType, new()
{
T t = new T();
if (t is IHasSome)
{
((IHasSome)t).BArray = new S();
}
return t;
}
If that doesn't fit, you can use reflection to go over the properties and check their types. Set the variable accordingly.
Solution 2
I agree with @PatrickHofman that way is better, but if you want somethig more generic that creates a new instance for all properties of a type, you can do that using reflection:
public T InitializeProperties<T, TProperty>(T instance = null)
where T : class, new()
where TProperty : new()
{
if (instance == null)
instance = new T();
var propertyType = typeof(TProperty);
var propertyInfos = typeof(T).GetProperties().Where(p => p.PropertyType == propertyType);
foreach(var propInfo in propertyInfos)
propInfo.SetValue(instance, new TProperty());
return instance;
}
Then:
// Creates a new instance of "C" where all its properties of the "B" type will be also instantiated
var cClass = InitializeProperties<C, B>();
// Creates also a new instance for all "cClass properties" of the "AnotherType" type
cClass = InitializeProperties<C, AnotherType>(cClass);
Comments
-
Mohammad Javad almost 2 years
class A
class A{ ... }
class B
class B:A{ ... }
class C
class C:A{ B[] bArray{get;set;} }
I would like to check if T has a property type of S , create instance of S and assignment to that propery :
public Initial<T,S>() where T,S : A{ if(T.has(typeof(S))){ S s=new S(); T.s=s; } }