maxp
maxp

Reputation: 25141

Elementary Casting (c#)

The following will compile but throw an exception:

public class a
{
    public string foo { get; set; }
}

public class b : a 
{

}

public class test()
{
   void Main()
   {
       b bar = (b)new a();
   }
}

Is the only option to construct a new instance of b, then manually copy each property/field from a?

Upvotes: 1

Views: 124

Answers (4)

wizzardz
wizzardz

Reputation: 5874

You should have used it other way around (as ChaosPandion mentioned)

 a bar = new b();

Upvotes: 0

ChaosPandion
ChaosPandion

Reputation: 78252

The problem is that a is not an instance of b. What your doing is essentially saying that an Animal is a Dog or that a Tool is a Hammer when in fact it is the other way around.

Upvotes: 3

Bjorkson
Bjorkson

Reputation: 671

Use 'as': b = new a() as b; Just notice to check if b is null after using 'as'. In your case you try to do upcasting since b inherite from a which isnt possiable in your case. if you try to achive polimorfisem you can do a = new b() as a;

Upvotes: 1

Oded
Oded

Reputation: 498904

You can't upcast like this in C# and expect valid results.

If b adds new members, an a object will not suddenly have them, however you try to cast it.

Say b adds a buzz() method. Suppose that your cast actually works. What happens when you call bar.buzz()?

Upvotes: 1

Related Questions