Prakash K

Prakash K

  • NA
  • 33
  • 0

Type Casting

Jul 23 2011 2:11 PM

Hi ... I have one doubt in casting 

  BaseClass bc = dc;  //1

  BaseClass bc1 = (BaseClass)dc;  //2

  BaseClass bc2 = new Derived();  //3 

  BaseClass bc3= dc as BaseClass;  //4 

these 4 lines produce same o/p. but what is difference in this?
which one is better ?



My simple code is here,

using System;
using System.Collections.Generic;
using System.Text;

namespace Example
{
class BaseClass
  {
  public void Method()
  {
  Console.WriteLine("This is Base Class");
  }
  }

  class Derived: BaseClass
  {
  new public void Method()
  {
  Console.WriteLine("This is Derived Class");
 
  } 
  }

  class Program
  {
  static void Main(string[] args)
  {
  Derived dc = new Derived();

  BaseClass bc = dc;  //1

  BaseClass bc1 = (BaseClass)dc;  //2

  BaseClass bc2 = new Derived();  //3 

  BaseClass bc3= dc as BaseClass;  //4 
 
  dc.Method();
  bc.Method();
  bc1.Method();
  bc2.Method();
  bc3.Method();
  }
  }
}





O/P

This is Derived Class
This is Base Class
This is Base Class
This is Base Class
This is Base Class


plz help me.. anybody

Answers (3)