The main problem of this question is when we pass T into some function and use it to cast some object like the following statement.
void SomeFunction<T> (object model)
{
(SomeClass<T>)model;
}
Everything works fine. But I want to cast model object to generic class object that is parent of T or grand parent of T depend on what is not empty. How to do that?
Updated # 1
For more understanding, please look at the following example.
public partial class SimpleUserInfo
{
public string LogOnName { get;set; }
public string HashedPassword { get;set; }
}
public partial class UserInfo : SimpleUserInfo
{
pubic string Address { get;set; }
}
After I create some data models. I create some generic class that use UserInfo class as parameter.
public class SimpleUserInfoValidator : IValidator<SimpleUserInfo>
{
// logic to validate simple user info instance
}
And then, I add attribute to SimpleUserInfo class.
[Validator(typeof(SimpleUserInfoValidator))]
public partial class SimpleUserInfo {}
Finally, I create some function for retrieving validator in given class T.
public GetValidator<T> ()
{
var attribute = (ValidatorAttribute)Attribute.GetCustomAttribute(type, typeof(ValidatorAttribute));
if (attribute == null || attribute.ValidatorType == null)
return null;
var (IValidator<T>)Activator.CreateInstance(attribute.ValidatorType);
}
This function will works fine when T is SimpleUserInfo but problem will occur when T is UserInfo. How to solve this?
PS. To solve this question does not require to use new feature of C# 4.0. But I just tell you about I will apply this solution in C# 4.0.
Thanks,
I haven’t installed .NET 4.0 yet, so I am not sure about using covariance properly, but you can get covariance support even in .Net 2.0 and 3.5 using a Duck Typing library (e.g. duck typing library by David Meyer or LinFu by Philip Laureano:
In other words, last line in
GetValidator<T>should look like this:or (using LinFu)
[Edit]
It is possible that I have not understood your question, but I believe it boils down to this:
You have a generic interface with a generic parameter of type T:
You want to cast it to the same generic interface, but with a generic parameter which is a base class of T:
Simple casting will not work, because generic type covariance is not supported (at least not in older versions of .Net):
But it will work using duck typing:
Once again, .Net 4.0 should handle covariance, but I haven’t tested it. This example will work in any .Net version, so I included it for completeness sake.