![]() |
|
Interfaces, Boxing and new keyword in C#, Free online C# Programming Tutorial... |
| Lessons | C# Interrfaces, Boxing, new |
|
The new operator In C++, the new keyword instantiates an object on the heap. In C#, with reference types, the new keyword does instantiate objects on the heap but with value types such as structs, the object is created on the stack and a constructor is called. You can, create a struct on the stack without using new, but be careful! New initializes the object. If you don't use new, you must initialize all the values in the struct by hand before you use it (before you pass it to a method, for example) or it won't compile. Boxing Boxing is converting any value type to corresponding object type and convert the resultant 'boxed' type back again, also called un-boxing. int i = 123; object box = i; // value of i is copied to the object box if (box is int){ // runtime type of box is returned as boxed value type Console.Write("Box contains an int"); // this line is printed } Interfaces Just like Java, C# also has interfaces that only contain method signatures. There are no access modifier and everything is implicitly public. It doest not have any fields, not even static ones. A class can implement many interfaces but unlike Java there is no implements keyword. Syntax notation is positional where we have base class first, then base interfaces as shown below: class X: CA, IA, IB { }
Next >>> Lesson No. 21: C# readonly, is, as
|