Please Explain me the code
A a = b as A;
Iam confused with it

public class A
   public virtual void One();
   public void Two();

public class B : A
   public override void One();
   public new void Two();

B b = new B();
A a = b as A;

a.One(); // Calls implementation in B
a.Two(); // Calls implementation in A
b.One(); // Calls implementation in B
b.Two(); // Calls implementation in B
5 Years
Discussion Span
Last Post by ddanbe

Hi Karan 4, welcome at Daniweb!
The as keyword is practically the same as a cast.
So line 14 could be written A a = (A)b;

Votes + Comments
Thanks ddanbe

The as keyword is practically the same as a cast.

The difference being that if the given object doesn't have the right type, a cast will throw an exception while as will just return null instead.

In this case however, there's no need to cast at all since A is a supertype of B. So the line in question should really just be A a = b;.

Votes + Comments
Good addition

Oh, and (as example) line 3 will not compile.
It must at least be something like this:
public virtual void One(){}

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.