Type Casting of Reference Types in Asp.net C#

Type Casting of Reference Types in Asp.net C#:



In this  post we try to understand Type Casting of Reference Types . in this post we are going to learn about Type casting of reference type with example in C#
A reference variable of type parent can refer to an object of child class
 because all the members which the reference variable can access exist in memory when the object is of child class.
A reference variable of child cannot refer to an object of parent class
 because the child class members that the reference variable can access do not exist in memory when the object is of parent class.

 C# Program Example:


 public class CParent
{
                public int PubA1;
                private int PriA1;
                protected int ProA1;
               
                public CParent()
                { }
               
                public CParent(int a, int b, int c) : this()
                {
                                this.PriA 1= a;
                                this.ProA1 = b;
                                this.PubA1 = c;
                }
}

public class CChild : CParent
{
                public int pubB; public CChild() //First calls parent class constructor.
                { }

                public CChild(int a, int b, int c, int d) : base(a, b, c)
                {
                                //this.PriA1 = a;
                                this.ProA1 =b;
                                this.PubA1 = c;
                                this.pubB1 = d;
                }
               
                public void Foo()
                {
                                CParent p = new CParent();
                                CChild c = new CChild();
                                ProA1 = 10;
                                c.ProA1 = 10;                                      }
}

class Program
{
                static void Main(string[] args)
                {
                                CChild b; b = new CChild(1, 2, 3, 4);
                                b.Foo();
                }

}


Asp.net Related Other Post :

Comments

Post a Comment