InvalidCastException: Activator.CreateInstance w/ Generic Inheriting Type?

It looks like you're actually calling: LoadServiceType(typeof(UserService)) That won't work, because it's trying to cast to IDataService strings = new List(); IList objects = strings; objects. Add(new object()); string firstString = strings0; // Eek!

It looks like you're actually calling: LoadServiceType(typeof(UserService)); That won't work, because it's trying to cast to IDataService when UserService actually implements IDataService You'll find that if you change your test code to try to cast using IDataEntity as a type argument instead of User, it'll fail in the same way. This is all to do with generic variance. It's a big topic - Eric Lippert has a whole series of blog posts on it and last year I gave a talk at NDC on it... I don't know if the streaming site with the talk on is still available, but you can grab a torrent of all the talks here.To give a very simple example, you can't cast an IList to IList in exactly the same way - otherwise this would compile, but have to fail at execution time: IList strings = new List(); IList objects = strings; objects.

Add(new object()); string firstString = strings0; // Eek!

Had a feeling about the IDataEntity malarkey. So, as per your IList example - regardless of the fact that User implements IDataEntity, I'm bound for failure, right? I'll test.

And thanks for the links + info, much appreciated. – Mr. Disappointment Apr 1 at 11:05 Ah, it would seem the constraint where TUserType : class, IUser, IDataEntity, new() on UserService prevents this: var be = (UserService)a;. Any ideas on correcting to achieve the desired behaviour?

– Mr. Disappointment Apr 1 at 11:09 @Mr. Disappointment: I'm not really sure what the desired behaviour is. Is there any reason you can't just use User instead of IDataEntity when you call LoadServiceType? – Jon Skeet Apr 1 at 11:19 @Jon Skeet: The idea is that we have a read-only collection of services that are loaded at runtime, where only one of them handles users but they all have common elements - the code doesn't necessarily know about UserService.

I'm thinking of a 'reach-out' method, like a type resolver though, so utilisers can help the library out some - not so sure yet though. – Mr. Disappointment Apr 1 at 11:27 @Mr. Disappointment: The caller doesn't know about UserService, but does it know about User? – Jon Skeet Apr 1 at 11:53.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions