C# Sharp QA-19 :👈 👉:Constructors in C#

C# (C-Sharp) Question Answers - 191-200

191. What Are Extension Methods?

Extension methods allow developers to add callable methods to an existing type without modifying that type or creating a derived type.

An extension method is declared as a static method in a non-nested, non-generic static class, and its first parameter uses the this modifier.

Example

public static class StringExtensions
{
    public static bool IsLongerThan(
        this string value,
        int length)
    {
        return value != null && value.Length > length;
    }
}

Usage:

string name = "Allamaprabhu";
bool result = name.IsLongerThan(5);
Console.WriteLine(result); // True

The compiler resolves this call to the corresponding static method. The original string type is not modified.

Benefits

  • Add convenient operations to existing types.
  • Improve readability and fluent-style APIs.
  • Work with types that cannot be modified directly.
  • Provide reusable helper behavior for interfaces and collections.

Limitations: Extension methods cannot access private members of the extended type. They also cannot override existing instance methods; when an applicable instance method exists, normal instance-method resolution takes precedence.

192. What Are Generics and Collections?

Generics

Generics allow classes, interfaces, methods, and delegates to work with specified types while preserving type safety and reuse.

Instead of creating separate classes for integers, strings, and other types, a generic class can operate on a type parameter such as T.

Example

public class Box<T>
{
    public T Value { get; set; }
}
Box<int> numberBox = new Box<int>
{
    Value = 100
};
Box<string> textBox = new Box<string>
{
    Value = "Hello"
};

The compiler checks the types used with each constructed generic type. Generics can also avoid boxing and unboxing when used with value types in appropriate scenarios.

Collections

Collections are data structures that store and manage groups of objects or values.

Common C# collection types include:

Collection Purpose
Array Stores a fixed-size sequence of elements.
List<T> Stores a resizable, ordered sequence of typed elements.
Dictionary<TKey, TValue> Stores key-value pairs for lookup by key.
HashSet<T> Stores unique elements according to its equality comparer.
Queue<T> Supports first-in, first-out processing.
Stack<T> Supports last-in, first-out processing.

Example of a Generic Collection

using System.Collections.Generic;
List<string> names = new List<string>();
names.Add("Ravi");
names.Add("Arun");
names.Add("Priya");
foreach (string name in names)
{
    Console.WriteLine(name);
}

Why Are Generics and Collections Used Together?

  • Type safety: A List<int> accepts integers rather than arbitrary object types.
  • Reusability: One generic implementation works with many types.
  • Performance: Generic collections can avoid boxing and unboxing for value types.
  • Maintainability: Types and intended operations are clearer.

193. What benefit do you get from using a Primary Interop Assembly (PIA)?

A Primary Interop Assembly (PIA) is a .NET assembly that contains the official managed definitions of types exposed by a COM component.

It allows .NET applications to interact with COM components, such as Microsoft Office applications, using managed code.

Benefits of PIA

  • Type safety: Provides managed definitions for COM types, interfaces, methods, and properties.
  • Consistency: Multiple applications can use the same official interop definitions.
  • Type identity: Helps .NET recognize COM types consistently across assemblies.
  • Simplified development: Developers can work with COM objects through familiar .NET types.

Example

using Microsoft.Office.Interop.Excel;
class Program
{
    static void Main()
    {
        Application excel = new Application();
        excel.Visible = true;
    }
}

Here, Microsoft.Office.Interop.Excel provides managed definitions for Excel's COM interfaces. The required interop assembly must be referenced by the project.

Interview summary: A PIA provides official, reusable managed type definitions for COM components, improving type safety and consistency when .NET applications interact with COM.


194. By what mechanism does NUnit know what methods to test?

NUnit is a unit-testing framework for .NET applications. It identifies test methods primarily through attributes and reflection.

Important Attributes

  • [TestFixture] identifies a class containing tests, although it is optional in many modern NUnit scenarios.
  • [Test] identifies a test method.
  • [TestCase] allows a test method to run with specified input values.
  • [SetUp] identifies a method that runs before each test in the fixture.
  • [TearDown] identifies a method that runs after each test in the fixture.

Example

using NUnit.Framework;
[TestFixture]
public class CalculatorTests
{
    [Test]
    public void Add_TwoNumbers_ReturnsSum()
    {
        int result = 10 + 20;
        Assert.That(result, Is.EqualTo(30));
    }
    [TestCase(2, 3, 5)]
    [TestCase(4, 6, 10)]
    public void Add_ReturnsExpectedResult(
        int a, int b, int expected)
    {
        Assert.That(a + b, Is.EqualTo(expected));
    }
}

How Does NUnit Discover Tests?

  1. The test runner or NUnit adapter loads the test assembly.
  2. NUnit uses reflection and its discovery mechanisms to identify test fixtures and methods marked with supported test attributes.
  3. The test runner executes the discovered tests.
  4. Assertions determine whether the tests pass or fail.

Interview summary: NUnit discovers tests using attributes and reflection, with the NUnit test engine and test runner coordinating test discovery and execution.


195. Explain What Happens in This Constructor. How Is This Construct Useful?

public class C
{
    public C(string a) : this()
    {
    }
    public C()
    {
    }
}

Explanation

The expression : this() is called constructor chaining. It invokes another constructor of the same class.

When the following constructor is called:

public C(string a) : this()
{
    // Additional initialization
}

The parameterless constructor executes first. After it completes, the body of the parameterized constructor executes.

Execution Flow

C("Hello")
    |
    v
C() executes first
    |
    v
C(string a) body executes

How Is It Useful?

Constructor chaining avoids duplicating common initialization logic across constructors.

public class Employee
{
    public string Name { get; }
    public string Department { get; }
    public Employee() : this("Unknown", "General")
    {
    }
    public Employee(string name, string department)
    {
        Name = name;
        Department = department;
    }
}

Both constructors use the same initialization logic. The parameterless constructor supplies default values, while the parameterized constructor initializes the properties.

Interview summary: this() calls another constructor in the same class, allowing constructors to reuse initialization logic and reduce code duplication.


196. What Is this? Can This Be Used Within a Static Method?

The this keyword refers to the current instance of a class. It is used in instance members to access the current object's fields, properties, methods, or constructors.

Example

public class Employee
{
    private string name;
    public Employee(string name)
    {
        this.name = name;
    }
    public void Display()
    {
        Console.WriteLine(this.name);
    }
}

In this.name = name, this.name refers to the instance field, while name refers to the constructor parameter.

Can This Be Used in a Static Method?

No. A static method belongs to the class itself rather than to a particular object. It has no current instance, so this cannot be used inside it.

public class Employee
{
    public void Display()
    {
        Console.WriteLine(this.ToString()); // Valid
    }
    public static void Show()
    {
        // Console.WriteLine(this); // Compilation error
    }
}

Interview summary: this refers to the current object and is available in instance members, not static members.


197. What Is a Partial Class?

A partial class allows a single class to be declared across two or more source files. The compiler combines the partial declarations into one class during compilation.

Example

Employee.cs

public partial class Employee
{
    public string Name { get; set; }
}

EmployeeDetails.cs

public partial class Employee
{
    public void Display()
    {
        Console.WriteLine(Name);
    }
}

Both declarations form a single Employee class.

Benefits

  • Splits a large class into manageable source files.
  • Supports code generation tools and designer-generated code.
  • Allows developers to separate generated code from manually written code.
  • Makes collaborative development easier in suitable scenarios.

Important Rules

  • Each declaration must use the partial keyword.
  • Declarations must represent the same type and be compiled into the same assembly and module.
  • Conflicting declarations, such as incompatible base classes or duplicate members, can cause compilation errors.

Interview summary: A partial class divides one logical class across multiple files while the compiler combines its declarations into one type.


198. What Are Serialization and Deserialization? Explain the Types of Serialization.

Serialization converts an object's data into a format that can be stored or transmitted.

Deserialization reconstructs an object or data structure from the serialized representation.

Example Using JSON

using System;
using System.Text.Json;
public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
}
class Program
{
    static void Main()
    {
        Employee employee = new Employee
        {
            Name = "Ravi",
            Age = 25
        };
        // Serialization
        string json = JsonSerializer.Serialize(employee);
        Console.WriteLine(json);
        // Deserialization
        Employee restored =
            JsonSerializer.Deserialize<Employee>(json);
        Console.WriteLine(restored.Name);
    }
}

Types of Serialization

Type Description Common Use
JSON Serialization Converts data into JavaScript Object Notation (JSON). Web APIs, configuration, and data exchange.
XML Serialization Converts supported object data into XML. Systems requiring XML-based data exchange.
Binary Serialization Represents data in a binary format. The format depends on the serializer. Specialized binary protocols or formats.
Data Contract Serialization Uses data contracts to define serialized data. Interoperability and service communication scenarios.

Important Security Note

BinaryFormatter is obsolete and unsafe for untrusted data. It should not be used for new development. Prefer JSON, XML, or a suitable documented binary format according to the application's requirements.

Why Is Serialization Useful?

  • Sending data between applications.
  • Storing data in files.
  • Communicating through APIs.
  • Persisting application state.
  • Transferring structured data over a network.

Interview summary: Serialization converts object data into a transferable or storable representation; deserialization reconstructs data from that representation.


199. What Are Covariance and Contravariance?

Covariance and contravariance describe how generic type parameters can vary according to inheritance relationships.

Suppose Dog inherits from Animal.

public class Animal { }
public class Dog : Animal { }

Covariance (out)

Covariance allows a generic type that produces a more derived type to be used where a less derived type is expected.

For example, IEnumerable<Dog> can be assigned to IEnumerable<Animal> because IEnumerable<T> is covariant.

IEnumerable<Dog> dogs = new List<Dog>();
IEnumerable<Animal> animals = dogs;

This is safe because every Dog is an Animal.

The out keyword indicates covariance in a generic interface or delegate declaration.

Contravariance (in)

Contravariance allows a generic type that consumes a less derived type to be used where a more derived type is expected.

Action<Animal> handleAnimal =
    animal => Console.WriteLine("Animal handled");
Action<Dog> handleDog = handleAnimal;
handleDog(new Dog());

An operation that can handle any Animal can also handle a Dog.

The in keyword indicates contravariance in a generic interface or delegate declaration.

Comparison

Feature Covariance Contravariance
Keyword out in
Main Role Produces values Consumes values
Direction More derived to less derived Less derived to more derived
Example IEnumerable<Dog> to IEnumerable<Animal> Action<Animal> to Action<Dog>

Important Rules

  • Variance applies to generic interfaces and delegates, not arbitrary generic classes.
  • A covariant type parameter is used in permitted output positions.
  • A contravariant type parameter is used in permitted input positions.
  • Variance conversions work for reference types; they do not provide the same conversions for value types.

Interview summary: Covariance (out) supports safe conversions for types that produce values, while contravariance (in) supports safe conversions for types that consume values.


200. What Is the Difference Between Readonly, Constant and Static?

These keywords have different purposes. readonly and const restrict assignment in different ways, while static makes a member belong to the type rather than to individual instances.

Feature const readonly static
Meaning Compile-time constant Field assignable at declaration or in an instance constructor Member belongs to the type
Assignment Must be initialized with a compile-time constant expression Can be assigned at declaration or in the appropriate constructor Depends on the member and its other modifiers
When Value Is Established At compile time During initialization or construction Depends on the member's initialization
Instance-Specific No; constants are implicitly static Yes, unless combined with static No, when applied to a field or property
Can It Be Changed Later? No Not after construction for an instance readonly field Depends on whether the static member is mutable or read-only

Example

public class Example
{
    public const double Pi = 3.14159;
    public readonly int Id;
    public static int Count;
    public Example(int id)
    {
        Id = id;
        Count++;
    }
}
  • Pi is a compile-time constant.
  • Id can be assigned in the constructor and cannot be reassigned afterward through normal C# code.
  • Count is shared by all instances of Example and can change.

Important Points

  • A const field must be initialized with a compile-time constant value.
  • A readonly field can hold a value determined at runtime, such as a constructor argument.
  • A static field is shared across instances of the type.
  • static readonly is valid and useful when a shared value is established at runtime but should not be reassigned after type initialization.
  • A readonly reference prevents reassigning the reference, but does not automatically make the referenced object immutable.

Interview summary: const represents a compile-time constant, readonly restricts when a field can be assigned, and static makes a member belong to the type rather than an individual instance.


Quick Revision Table

Question Key Answer
PIA Provides managed type definitions for COM interoperability.
NUnit Uses test attributes and reflection for test discovery.
this() Calls another constructor in the same class.
this Refers to the current instance; unavailable in static methods.
Partial Class Splits one class declaration across multiple files.
Serialization Converts object data into a storable or transferable representation.
Covariance out; supports safe conversions for producers.
Contravariance in; supports safe conversions for consumers.
Constructors Initialize objects or type state.
const Compile-time constant.
readonly Field assignable during permitted initialization or construction.
static Member belongs to the type.
Array Fixed-size, strongly typed collection.
ArrayList Resizable, non-generic collection of objects.
List<T> Resizable, strongly typed generic collection.
XAML Declarative UI markup processed through framework-specific loading or compilation.
WeakReference Does not keep an object alive by itself.
Strong typing Provides stronger type checking and helps detect errors early.
using Imports namespaces or ensures disposable resources are disposed of.
const / readonly / static Compile-time constant, restricted reassignment, and type-level member respectively.
Array / ArrayList / List<T> Fixed-size typed storage, legacy resizable object collection, and resizable typed collection.
CLR memory management Manages allocation and garbage collection for managed objects.
var / dynamic Compile-time type inference versus runtime binding.
Component containers Examples include COM+, IIS, and Windows Services as hosting environments.
Value / reference types Value copying versus references to shared objects.
ref / out Pass variables by reference; out must be assigned before normal return.
Extension methods Add callable methods to existing types without modifying them.
Generics and collections Reusable type-safe code and data structures for groups of elements.
virtual / override / abstract / sealed Control polymorphism, required implementations, and inheritance.
Garbage collection Reclaims unreachable managed objects using generational collection.
Finalize / Dispose Finalization is non-deterministic; disposal supports timely cleanup.
using Ensures disposal when the scope ends.
override / new Override uses virtual dispatch; new hides an inherited member.
IDisposable Defines a standard resource-disposal contract.
ICloneable Defines cloning but does not specify shallow versus deep copying.
tasklist /m Lists processes with matching loaded modules.
catch(Exception) Can hide unexpected failures if used without appropriate handling.
FullTrust / GAC Primarily legacy .NET Framework security concepts.
Debug / Release Different build configurations; measure performance rather than assume.
JIT Traditionally compiles methods as required, with runtime-specific variations.
DateTime.Parse Can throw or interpret input differently; use TryParse or TryParseExact appropriately.
Double-checked locking Requires correct synchronization and memory visibility; Lazy<T> is often simpler.
Security attributes Legacy CAS demands are not a modern .NET sandboxing solution.
gacutil /l Lists GAC assemblies in .NET Framework environments.
sn -t Displays a strong-name public key token.
DCOM Uses port 135 for endpoint discovery and additional RPC endpoints for communication.
XmlSerializer Maps .NET objects to and from XML; permissions depend on runtime and configuration.
PropertySpecified Distinguishes an omitted XML element from an explicitly supplied default value.
Parameter attributes Supply metadata used by compilers, frameworks, and interop services.
🔙
C# Sharp QA-19 :👈 👉:Constructors in C#