C# multiple choice questions on destructors in class in C# Programming Language.
1. Which operator among the following signifies the destructor operator?
a) ::
b) :
c) ~
d) &
Answer: c
Clarification: None.
2. The method called by clients of a class to explicitly release any resources like network, connection, open files etc. When the object is no longer required?
a) Finalize()
b) End()
c) Dispose()
d) Close()
Answer: c
Clarification: Dispose() is only method called by clients of a class to explicitly release any resource like network connection, open files etc. When object is no longer required. Hence, Dispose() provides programmer with such programming control.
3. Name a method which has the same name as that of class and which is used to destroy objects also called automatically when application is finally on process of being getting terminated.
a) Constructor
b) Finalize()
c) Destructor
d) End
Answer: c
Clarification: Definition of the destructor.
4. Which of the following statements are correct?
a) There is one garbage collector per program running in memory
b) There is one common garbage collector for all programs
c) To garbage collect an object set all references to it as null
d) Both There is one common garbage collector for all programs & To garbage collect an object set all references to it as null
Answer: d
Clarification: None.
5. Operator used to free the memory when memory is allocated?
a) new
b) free
c) delete
d) none of the mentioned
Answer: c
Clarification: ‘New’ is used to allocate memory in the constructors. Hence, we should use ‘delete’ to free that memory.
6. Select wrong statement about destructor in C#?
a) A class can have one destructor only
b) Destructors cannot be inherited or overloaded
c) Destructors can have modifiers or parameters
d) All of the mentioned
Answer: c
Clarification: None.
7. What will be the output of the following C# code?
-
class sample -
{ -
int i;
-
double k;
-
public sample (int ii, double kk)
-
{ -
i = ii;
-
k = kk;
-
double j = (i) + (k);
-
Console.WriteLine(j);
-
} -
~sample()
-
{ -
double j = i - k;
-
Console.WriteLine(j);
-
} -
} -
class Program -
{ -
static void Main(string[] args)
-
{ -
sample s = new sample(8, 2.5);
-
Console.ReadLine();
-
} -
}
a) 0 0
b) 10.5 0
c) Compile time error
d) 10.5 5.5
Answer: d
Clarification: First constructor ‘sample’ is called and hence then destructor ‘~sample’ is evaluated.
Output :
