| C# Sharp QA-16 :👈 | 👉:C# Sharp QA-18 |
C# (C-Sharp) Question Answers - 161-170 |
161. Explain the Use of virtual, sealed, override, and abstract
These keywords control inheritance, method implementation, and polymorphism in C#.
| Keyword | Purpose | Explanation |
|---|---|---|
virtual |
Allows overriding | A base class method can provide a default implementation that derived classes may override. |
override |
Replaces inherited behavior | A derived class provides a new implementation of an inherited virtual or abstract member. |
abstract |
Requires implementation | An abstract member has no implementation in the declaring class and must be implemented by a non-abstract derived class. |
sealed |
Prevents further extension | A sealed class cannot be inherited. A sealed override prevents further overriding of that member. |
Example
public abstract class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal sound");
}
public abstract void Move();
}
public class Dog : Animal
{
public sealed override void Speak()
{
Console.WriteLine("Bark");
}
public override void Move()
{
Console.WriteLine("Dog walks");
}
}
Explanation:
Animalis abstract and cannot be instantiated directly.Speak()is virtual and has a default implementation.Move()is abstract and must be implemented by a concrete derived class.Dogoverrides both methods.sealed overrideprevents a further derived class from overridingSpeak().
162. How Does the Generational Garbage Collector in the .NET CLR Manage Object Lifetime? What Is Non-Deterministic Finalization?
The .NET Common Language Runtime (CLR) uses a garbage collector (GC) to automatically reclaim memory occupied by managed objects that are no longer reachable.
Generational Garbage Collection
The GC organizes most managed objects into three generations based on their age.
| Generation | Purpose |
|---|---|
| Generation 0 | Contains newly allocated, short-lived objects. It is collected frequently. |
| Generation 1 | Acts as an intermediate generation for objects that survive a Generation 0 collection. |
| Generation 2 | Contains longer-lived objects that survive multiple collections. Collections are generally more expensive. |
How It Works
- Objects are allocated on the managed heap.
- The GC identifies reachable objects by examining roots such as active stack references, static references, and runtime-managed handles.
- Unreachable objects become eligible for collection.
- The GC reclaims their memory and may compact the heap to reduce fragmentation.
- Objects that survive a collection may be promoted to an older generation.
The GC also manages the Large Object Heap (LOH), which generally holds objects around 85,000 bytes or larger, subject to runtime-specific details. Large objects are generally allocated in Generation 2 for collection purposes.
What Is Non-Deterministic Finalization?
Non-deterministic finalization means that you cannot predict exactly when the runtime will execute an object's finalizer, if the object has one.
public class Sample
{
~Sample()
{
Console.WriteLine("Finalizer executed");
}
}
The finalizer may execute after the object becomes unreachable and a garbage collection processes it. Its execution can be delayed, and it is not guaranteed to occur immediately when an object is no longer needed.
Important: Garbage collection manages managed memory, but it does not automatically guarantee timely release of unmanaged resources such as file handles or native operating-system handles. Use IDisposable for deterministic resource cleanup.
163. What Is the Difference Between Finalize() and Dispose()?
Finalize() and Dispose() are associated with resource cleanup, but their timing and purpose differ.
| Feature | Finalize | Dispose |
|---|---|---|
| Invocation | Executed by the runtime's finalization mechanism. | Called explicitly by the consumer or through a using statement. |
| Timing | Non-deterministic. | Deterministic when invoked correctly. |
| Purpose | Provides a fallback cleanup mechanism for unmanaged resources. | Releases resources promptly when they are no longer required. |
| Interface | Finalization is associated with a finalizer, written using destructor syntax in C#. | Typically exposed through the IDisposable interface. |
| Performance | Can add GC and finalization overhead. | Generally avoids finalization overhead when no finalizer is required. |
Example
public sealed class FileResource : IDisposable
{
private bool _disposed;
public void Dispose()
{
if (_disposed)
return;
// Release owned resources here.
_disposed = true;
GC.SuppressFinalize(this);
}
}
Note: Dispose() is a method, whereas a C# finalizer is declared using destructor syntax, such as ~FileResource(). A class needs a finalizer only when it directly owns unmanaged resources that require such a fallback; most classes should not implement one.
164. How Is the using() Pattern Useful?
The using statement ensures that an object implementing IDisposable is disposed of when execution leaves the relevant scope, including when an exception occurs.
Example
using (var reader = new StreamReader("data.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
When the block finishes, reader.Dispose() is called automatically.
The code is conceptually similar to:
var reader = new StreamReader("data.txt");
try
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
finally
{
if (reader != null)
reader.Dispose();
}
Benefits:
- Releases resources promptly.
- Reduces resource leaks.
- Works correctly when exceptions occur.
- Makes cleanup code easier to read and maintain.
Modern C# also supports a using declaration:
using var reader = new StreamReader("data.txt");
string content = reader.ReadToEnd();
With a using declaration, disposal occurs at the end of the enclosing scope.
165. Juxtapose the Use of override with new. What Is Shadowing?
override and new are used for different purposes when a derived class declares a member with the same name as a base class member.
| Feature | override | new |
|---|---|---|
| Purpose | Changes the implementation of a virtual or abstract base member. | Hides a member inherited from the base class. |
| Polymorphism | Uses virtual dispatch. | Member selection depends on the compile-time type of the reference. |
| Base member requirement | Must be virtual, abstract, or already overridden. | Does not require a virtual base member. |
Example of override
class Base
{
public virtual void Show()
{
Console.WriteLine("Base");
}
}
class Derived : Base
{
public override void Show()
{
Console.WriteLine("Derived");
}
}
Base obj = new Derived();
obj.Show(); // Derived
Example of new
class Base
{
public void Show()
{
Console.WriteLine("Base");
}
}
class Derived : Base
{
public new void Show()
{
Console.WriteLine("Derived");
}
}
Base obj = new Derived();
obj.Show(); // Base
Derived obj2 = new Derived();
obj2.Show(); // Derived
Shadowing (method hiding) occurs when a derived class declares a member that hides a member of the same name in its base class. The new keyword explicitly indicates this intent and suppresses the corresponding hiding warning.
166. What Is IDisposable? How Does It Support Deterministic Finalization?
IDisposable is a .NET interface that defines a single method:
public interface IDisposable
{
void Dispose();
}
It provides a standard way to release resources when an object is no longer required.
Example
public class ResourceManager : IDisposable
{
public void Dispose()
{
// Release unmanaged resources
// and dispose of owned disposable objects.
}
}
Usage:
using var manager = new ResourceManager();
// Work with manager.
// Dispose() is called at the end of the scope.
How does it support deterministic cleanup?
The consumer can call Dispose() at a known point in the program. The using statement or declaration automates that call at the end of the scope.
Strictly speaking, this is deterministic resource disposal, not deterministic finalization. Finalizers remain controlled by the runtime and are non-deterministic.
167. Explain ICloneable
ICloneable is a .NET interface that defines a Clone() method returning an object representing a copy of the original object.
public interface ICloneable
{
object Clone();
}
Example
public class Employee : ICloneable
{
public int Id { get; set; }
public string Name { get; set; }
public object Clone()
{
return new Employee
{
Id = Id,
Name = Name
};
}
}
Usage:
Employee original = new Employee
{
Id = 1,
Name = "Ravi"
};
Employee copy = (Employee)original.Clone();
Types of Cloning
- Shallow copy: Copies the object's fields. References to nested reference-type objects are copied, not the referenced objects themselves.
- Deep copy: Creates independent copies of the relevant nested objects as well.
Important: ICloneable does not specify whether cloning must be shallow or deep. For public APIs, a clearly named method such as DeepCopy() or a strongly typed copy method is often preferable.
168. What Does This Command Line Do? tasklist /m "mscor*"
tasklist /m "mscor*"
This Windows command lists running processes that have loaded modules whose names match the wildcard pattern mscor*.
tasklistlists running processes./mfilters processes by loaded module name."mscor*"matches module names beginning withmscor, such asmscorlib.dllwhere applicable.
It can help identify processes that have loaded certain .NET-related modules. It does not list every .NET process reliably, and the results depend on the runtime and modules loaded by each process.
9. Why Is catch(Exception) Almost Always a Bad Idea?
Catching Exception without a specific reason can hide unexpected failures, make debugging harder, and allow an application to continue in an invalid state.
Bad Example
try
{
ProcessOrder();
}
catch (Exception)
{
// Ignore the error.
}
This code silently discards potentially serious errors.
Better Example
try
{
ProcessOrder();
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
Catch specific exceptions when you can handle them meaningfully. A broad catch may be appropriate at an application boundary for logging, cleanup, or controlled error reporting, provided the application handles the failure safely and does not silently swallow it.
Best practices:
- Catch only exceptions you can handle appropriately.
- Do not use exceptions as normal control flow.
- Log useful diagnostic information without exposing secrets.
- Rethrow with
throw;when you need to preserve the original exception stack trace. - Use
finallyorusingfor cleanup rather than relying on a catch block.
170. What Is FullTrust? Do GAC'ed Assemblies Have FullTrust?
FullTrust is a legacy .NET Framework Code Access Security (CAS) concept. Code running with full trust was not restricted by the CAS permission set that applied to partially trusted code.
GAC stands for Global Assembly Cache. In .NET Framework, it stores shared assemblies that can be used by multiple applications.
Under the traditional .NET Framework CAS policy, assemblies loaded from the GAC were generally granted FullTrust by default. However, this should not be interpreted as a universal security guarantee for every deployment or hosting configuration.
Important distinctions:
- Being in the GAC is not the same as being digitally trusted by every security mechanism.
- Strong naming identifies an assembly's identity; it does not prove that the code is safe.
- Modern .NET does not use the legacy CAS sandboxing model in the same way as .NET Framework.
- FullTrust does not bypass operating-system permissions or every other security boundary.
| C# Sharp QA-16 :👈 | 👉:C# Sharp QA-18 |