0

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
3
Contributors
3
Replies
20
Views
3 Years
Discussion Span
Last Post by ddanbe
Featured Replies
  • 1
    ddanbe 2,525   3 Years Ago

    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;** Read More

  • 2

    > 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` … Read More

  • 1
    ddanbe 2,525   3 Years Ago

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

1

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;

Comments
Thanks ddanbe
2

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

Comments
Good addition
1

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.