I ran into an issue with generics which I believed can be solved with covariance, but don't fully understand how covarience works and how it can be declared properly. Let's say I have the following interfaces and classes:
public interface IOwnedObject<TUser>
where TUser : IBaseUser
{
string UserId { get; set; }
TUser User { get; set; }
}
public interface IBaseUser
{
string Id { get; set; }
}
public class User : IBaseUser
{
public string Id { get; set; }
}
public class SomeOwnedObject : IOwnedObject<User>
{
public string UserId { get; set; }
public User User { get; set; }
}
Then consider the following code:
var obj = new SomeOwnedObject();
if(obj is IOwnedObject<IBaseUser> o)
Console.WriteLine("Success"); // This never executes
The above if statement does not evaluate to true. However, in IOwnedObject
it's only ever possible for TUser
to be IBaseUser
.
The following code evaluates to true:
var obj = new SomeOwnedObject();
if(obj is IOwnedObject<User> o)
Console.WriteLine("Success"); // This executes
since User
implements IBaseUser
, shouldn't IOwnedObject<IBaseUser>
technically be a base class of IOwnedObject<User>
. Is it possible to make that first statement evaluate to true without referencing the concrete implementation User
?