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

Recommended Answers

All 3 Replies

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;

commented: Thanks ddanbe +0

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;.

commented: Good addition +14

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.