I have shared validation logic which largely depends on custom attributes, so I need to check that for each type.
An instance (to check against) is fetched for each validation subscriber:
var instance = this.ValidationProvider.GetInstanceForSubscriber(validationSubscriber);
Where validationSubscriber
is an enum with these values:
Person, Checks
At this time, GetInstanceForSubscriber
returns an instance of type object:
public object GetInstanceForSubscriber(ValidationSubscribers validationSubscriber)
{
switch (validationSubscriber)
{
case ValidationSubscribers.Person:
return new Person();
case ValidationSubscribers.Checks:
return new Checks();
default:
return null;
}
}
After calling this method, I check the type:
var instanceType = instance.GetType();
And then, I read the (custom) attributes:
var attributes = propertyInfo.GetCustomAttributes(true);
I then return a list of IEnumerable<PropertyAttribute>
which contains only my custom attributes, limiting the validation scale to what's necessary only (which is FYI, because not very relevant for this question).
The issue
As instance
is of type object, it does not contain any of my custom attributes (logically), so I need to cast it to the correct Class Type.
What's the best way to achieve this?