Types in C#: Value Types (Byte, Int, Float, Bool, Char, Struct)
Types in C#: Value Types (Byte, Int, Float, Bool, Char, Struct)
STACK
int i = 123;
int j = i;
i
123
int i = 123;
j
123
int j = i;
class Test
{
static void Main() {
int i = 10;
object o = i; // boxing
int j = (int) o; // unboxing
}
}
Polymorphsm
A a = new B();
a.Draw();
Output - A: Draw()
Compiler warning –
'B.Draw()' hides inherited member 'A.Draw()'. Use the new keyword if hiding was intended.
Using Virtual and Override – Allows us to invoke implementations of derived class methods from a base
class reference.
class A
{
public virtual void Draw()
{
Console.WriteLine("A: Draw()");
}
}
class B : A
{
public override void Draw()
{
Console.WriteLine("B: Draw()");
}
}
A a = new B();
a.Draw();
Output - B: Draw()
Abstract
Abstract class can have non-abstract (concrete) methods, while for interface; all methods have to be
abstract.
A class can inherit one or more interfaces, but only one abstract class.
Ans – Yes
Though we can not initialize an abstract class, an abstract class constructor is called
during the instantiation of derived class, just before derived class constructor.
Interview Question – Can we call abstract method from abstract class constructor?
Ans – Yes
It will be invoked when we instantiate a derived class. The abstract method’s overridden
version will be called.
Sealed
NOTE - If we want to declare a method as sealed, then it has to be declared as virtual in its base class.
The means only put sealed modifier on a method that overrides a virtual method of base class to
prevent further derived classes from overriding the specific implementation.
Interface
Const – compile time constant
We can only initialize a const variable to a compile time value, i.e., a value available to the compiler
while it is executing.
Once initialized at the time of declaration (compile-time), we cannot re-initialize a const variable.
NOTE - new() actually gets executed at runtime and therefore does not get value at compile time.
So this results in an error. So, const field of a reference type other than string can only be
initialized with null