Re: Activator Question

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Dan Dorey <dandorey1@xxxxxxxxx> wrote:
My goal is to pass in an assembly and have the method return an
instance of any classes that inherit from the generic type T.

My problem is that I'm unable to cast from the result of
Activator.CreateInstance(curType) to T even though curType is a
concrete class of T (T is abstract in this case). I'm unsure why I
can't make this cast. In another method where I don't have the
restriction of T being a class, this approch works fine when T is an
interface.

I kind of feel like I'm going about this the wrong way, so if anyone
has suggestions on a better approach, please let me know :)

Well, instead of InheritsFrom, you'd be better off using
Type.IsAssignableFrom or Type.IsSubclassOf.

However, I don't get any compile-time errors with your code.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
.



Relevant Pages

  • Re: Activator Question
    ... instance of any classes that inherit from the generic type T. ... can't make this cast. ... public class MySecondWidget: Widget { ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: newbie question sabout class design
    ... important is not to inherit from the list class - but rather create a ... overriding the original methods. ... I'm probably doing it wrong because I still have to cast. ... (with no parameter specification) indicates calling the ...
    (comp.lang.pascal.delphi.misc)
  • Re: To inherit or not to
    ... I think the author means, don't publicly inherit from a concrete class, ... useable in the same context as the base class. ...
    (comp.lang.cpp)
  • Re: How to Type cast ArrayList items to class objects
    ... i will reuse the vb class in c# and from the c# ... library i will return the class object and in vb i will type cast the ... just inherit from the C# class then you can add your function ...
    (microsoft.public.dotnet.languages.vb)
  • RE: Testing for a type at runtime.
    ... > A and B inherit from C. ... > C obj = GenerateReply ... > to cast it to an A and the method that I would like to use is 'as'. ... words, for compile-time reasons. ...
    (microsoft.public.dotnet.framework)