Casting and Generics

Given the following code:

public interface IUser{ ... } public class UserModel : IUser{ ... } 

and the steptup.cs

 services.AddScoped<UserManager<IUser>>(provider => { UserManager<UserModel> um = new UserManager<UserModel>( ... ); return (UserManager<IUser>)um; // <-- casting error } 

The error i get is that UserManager<UserModel> cannot be converted to UserManager<IUser>

even though UserModel implements IUser.

I’m trying to type the user manager to the interface type because in some projects my login api is backed by a mongo implementation and some are backed by mysql, but the rest api is the same regardless.

I’ve mostly been working in java where this would be valid, we’ve recently switched to c# and i’m having some issues understanding the way polymorphism works with generics

submitted by /u/myrddraa11
[link] [comments]

Leave a Reply