Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

Base to Derived is possible(Boxing), But Derived to base gives run time exception, however that is equivalent to Unboxing

$
0
0

class SampleClass
{
   public int i = 10;
}
class MainClass
{
   static void Main()
   {
      object a;
      a = 1;   // an example of boxing
      Console.WriteLine(a);
      Console.WriteLine(a.GetType());
      Console.WriteLine(a.ToString());
      a = new SampleClass();
      SampleClass classRef;
      classRef = (SampleClass)a; //Example of Unboxing
      Console.WriteLine(classRef.i);
   }
}

All classes in .net implicitly inherited from Object Class.In above code

classRef = (SampleClass)a; //Example of Unboxing is possible.

 class BaseSample
    {
        public int ii = 10;
    }
    class SampleClass:BaseSample
    {
        public int i = 10;
    }

    class MainClass
    {
        static void Main()
        {

  SampleClass classRef;

    BaseSample b = new BaseSample();
            b.ii = 90;

   classRef = (SampleClass)b; //Getting Run time Exception

}

Why I am gettting run time exception,

Boxing and UnBoxing is possible

 public int ConvertToINT(object obj)
        {
            int i = (int)obj;
            return Convert.ToInt32(obj);
        }
        public string CovertToString(object obj)
        {
            string s = (string)obj;
            //return Convert.ToString(s);
            return s;
        }

Convert.ToInt32(obj); This is Base to derived and possible,

Butwhen

Base b=new Base();

Child c=(Child)b;//Gives run time exception

Why is it So.

Please help


Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>