Re: Casting a parent class to a child class

Tech-Archive recommends: Fix windows errors by optimizing your registry




B could be cast to A. A could not be cast to B.
Imagine if you could cast A to B, what if you call test.Label2, which
is not a member of class A.

S. Lorétan wrote:
Hi guys,

Sorry for this stupid question, but I don't know why it isn't working.

Here is my (example) code:

namespace Test {
class A {
public string Label1;
}

class B : A {
public string Label2;
}

class Program {
static void Main(string[] args) {
A test = new A();
B test2 = (B)test;
}
}
}

It work fine with the compiler, but when executing, it ends with an
InvalidCastException error. Why?

Thank you.

.



Relevant Pages

  • Re: Databinder.Eval passed as argument is choking
    ... > TemplateColumn instead of a BoundColumn so I can pass the value into a ... > function won't take the value seemingly no matter how I cast or don't cast ... > public string FormatYesOrNo ... > I tried casting the late bound info the aspx to a bool (e.g. ...
    (microsoft.public.dotnet.framework.aspnet.datagridcontrol)
  • Re: ArrayList pass to method
    ... if you use a Listyou won't have to use a cast at all. ... class PrevPrintJobs ... public string name; ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: checkbox databind does not work
    ... DataBinder.Eval will give you an object, not an int. ... need to cast it or teach fbool to deal with it. ... public string fbool ...
    (microsoft.public.dotnet.framework.aspnet)
  • Storing a class in the ViewState
    ... ViewState and retrieve the class upon postback. ... However I get a cast ... exception. ... public string x1; ...
    (microsoft.public.dotnet.framework.aspnet.webcontrols)
  • Re: FLAT Christine Brewer (SF Fidelio) FLAT Debbie Void (NY concert) FLAT FLAT FLAT
    ... and poorly sung new "Traviata" from Deutsche Grammophon with Netrebko, Villazon and Hampson. ... Not one true Verdian in the cast. ... Can you imagine? ...
    (rec.music.opera)