RE: Testing for a type at runtime.

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

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 05/04/04


Date: Tue, 4 May 2004 18:39:26 +0100

Kevin Burton <anonymous@discussions.microsoft.com> wrote:
> I need the cast because C# methods require it. Again using my example
> A and B inherit from C.
>
> C obj = GenerateReply()
> . . .
> ProcessReply(obj); // Compiler will not allow this. A cast must be done.
> . . .
> ProcessReply(A obj)
> {
> }
>
> I cannot call ProcessReply with C even though it may be an A. I have
> to cast it to an A and the method that I would like to use is 'as'.

The reason you need to do that is for the C# compiler though - in other
words, for compile-time reasons. Could you give an example of how you
want to use it at run time instead?

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


Relevant Pages

  • RE: Testing for a type at runtime.
    ... Again using my example A and B inherit from C. ... C obj = GenerateReply ... // Compiler will not allow this. ... A cast must be done. ...
    (microsoft.public.dotnet.framework)
  • Re: Confused about using Reflection to examine a collection
    ... the precise type that Reflection is saying it is. ... say that 'obj' is actually a custom collection. ... If it were a basic type, such as 'string' then I would do a cast like this: ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Confused with Generics
    ... use that can't be accomplished with a cast isn't allowed. ... The common workarounds are to use a template or factory in the Gen class, ... You can do similar stuff by reflecting on the templateObject, ... private T obj; ...
    (comp.lang.java.programmer)
  • Re: If the object is an instance of a class, why was it cast?
    ... // why cast obj if it is an instance of Book? ... the compiler is very sure that, ... But, if you dont cast it, and just make the statement like, ... read about Generics of Java ...
    (comp.lang.java.programmer)
  • 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)