views:

108

answers:

2

I am trying to dynamically load my authentication server type based on a setting. I am hung up on how to cast to a type when I don't know the type.

   Type t = Type.GetType(WebConfigurationManager.AppSettings.Get("AuthenticationSvcImpl"));
    IAuthenticationService authCli = Activator.CreateInstance(t);
    return authCli.AuthenticateUser(login);

I know there is Convert.ChangeType(), but that just converts to an object...

+2  A: 
var authCli = Activator.CreateInstance(t) as IAuthenticationService;
leppie
this did the trick... don't really understand though--why var?
jle
`var` is just there to save space, else the line was to long, and I was to lazy to split it :) `var` == `IAuthenticationService` in this scenario. Basically, your type IS known at compile time, not the actual type, but the compatible interface type.
leppie
A: 

Is that what you are looking for ?

Type t = Type.GetType(WebConfigurationManager.AppSettings.Get("AuthenticationSvcImpl"));
IAuthenticationService authCli = (IAuthenticationService) Activator.CreateInstance(t);
return authCli.AuthenticateUser(login);
Laurent Etiemble