OOPs Interview Questions
private string m_Color;;
public string Color
{
get
{
return m_Color;
}
set
{
m_Color = value;
}
}
Car Maruti = new Car();
Maruti.Color= “White”;
Console.Write(Maruti.Color);
What is Constructor?
• A constructor is a special method whose task is to initialize the object of its class.
• It is special because its name is the same as the class name.
• They do not have return types, not even void and therefore they cannot return values.
• They cannot be inherited, though a derived class can call the base class constructor.
• Constructor is invoked whenever an object of its associated class is created.
• Note: There is always at least one constructor in every class. If you do not write a constructor, C# automatically provides one for you, this is called default constructor. Eg: class A, default constructor is A().
Static Members of the class?
Static members belong to the whole class rather than to individual object Static members are accessed with the name of class rather than reference to objects.
class Test
{
public int rollNo;
public int mathsMarks;
public static int totalMathMarks;
}
class TestDemo
{
public static void main()
{
Test stud1 = new Test();
stud1.rollNo = 1;
stud1.mathsMarks = 40;
stud2.rollNo = 2;
stud2.mathsMarks = 43;
Test.totalMathsMarks = stud1.mathsMarks + stud2.mathsMarks;
}
}
What is a Static Method of the class?
Methods that you can call directly without first creating an instance of a class. Eg: Main() Method, Console.WriteLine() You can use static fields, methods, properties and even constructors which will be called before any instance of the class is created. As static methods may be called without any reference to object, you can not use instance members inside static methods or properties, while you may call a static member from a non-static context. The reason for being able to call static members from non-static context is that static members belong to the class and are present irrespective of the existence of even a single object.
Whats is Static Constructor?
In C# it is possible to write a static no-parameter constructor for a class. Such a class is executed once, when first object of class is created.
One reason for writing a static constructor would be if your class has some static fields or properties that need to be initialized from an external source before the class is first used.
Eg:
Class MyClass
{
static MyClass()
{
//Initialization Code for static fields and properties.
}
}
What is a Destructor?
A destructor is just opposite to constructor.
It has same as the class name, but with prefix ~ (tilde).
They do not have return types, not even void and therefore they cannot return values.
destructor is invoked whenever an object is about to be garbage collected
class person
{
//constructor
person()
{
}
//destructor
~person()
{
//put resource freeing code here.
}
}