Pages

Sunday, May 12, 2013

new keyword in c#

In C#, the new keyword can be used as an operator or as a modifier.
  • new operator   Used to create objects on the heap and invoke constructors.
  • new modifier   Used to hide an inherited member from a base class member. 
Note:
  For suppressing the warning message generated by the c# compiler when hidding the intended

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   // inheritance
 {
  new public int x=20;         // ussing new keyword
  new public string y="palle";   //ussing new keyword
 }
}
Note:
   It is used mostly in downcasting method for derive class variable ussing new keyword.
If base class variable name same as derive class variable

No comments:

Post a Comment