Pages

Monday, May 13, 2013

Upcasting and downcasting in C#

Downcasting:

By taking child class object referance  CLR will find the parent class referance

Sample code:

{
B b=new B();
Response.write(b.x);
Response.write(b.y);
A a=b;           // downcasting
Response.write(a.x);
Response.write(a.y);
 }
}
public class A
 {
   public int x=10;
  public string y="hello";
}
public class B:A
{
  public int x=20;
   public string y="palle";
}

Upcasting:

In case of upcasting technique CLR identify the child class object  referance by using parent  class object

sample Code:

public partial class inh : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Student2 s2 = new Student2();
        Student1 s1 = s2;              //Downcasting which is implicit operation
        Response.Write(s1.name);                      
        Response.Write(s1.stud_id);
       Student2 s3 = (Student2)s1;   //Upcasting which is explicit operation
        Response.Write(s3.name);               //Output--->Kripa
        Response.Write(s3.stud_id);           //Output--->1002
         }
}
public class Student1
{
     public string name = "kumar";
     public int stud_id = 1001;
 }
 public class Student2 : Student1
 {
      public string name = "Kripa";
      public int stud_id = 1002;
 }
 }
Note:

->In the above sample code first downcasting operation performswhere finding the parent 
class object reference through the child class object reference(Student s1=s2)
,where s1 is parent class object and s2 is child class object.
->By using parent class object reference we have to find child class 
object reference which is upcasting 
->(Student2 s3=(Student2)s1),where s3 is child class object and s1 is parent parent
 class object. 






No comments:

Post a Comment