| C# Sharp QA-18 :👈 | 👉:C# Sharp QA-20 |
C# (C-Sharp) Question Answers - 181-190 |
181. Can Attributes Be Placed on Specific Parameters to a Method? Why Is This Useful?
Yes. C# supports attributes on method parameters. Parameter attributes provide metadata that tools, frameworks, compilers, or runtime components can use.
Example
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
public void Update(
[In] int input,
[Out] out int result)
{
result = input * 2;
}
public void Log(
[CallerMemberName] string memberName = "")
{
Console.WriteLine(memberName);
}
The example above illustrates parameter metadata for interop and compiler-supported features. In practice, CallerMemberName must be imported from System.Runtime.CompilerServices, and the Log method should use that namespace.
Common Uses
- Interop: Attributes such as
[In],[Out], and[MarshalAs]help control data marshaling across managed and unmanaged boundaries. - Compiler-supported behavior: Attributes such as
[CallerMemberName]can supply the calling member name automatically. - Nullability analysis: Attributes such as
[NotNull]and[MaybeNull]can communicate nullability contracts to compiler analysis tools. - Framework metadata: Frameworks and libraries can define custom parameter attributes to influence validation, binding, documentation, or other behavior.
Important: An attribute is metadata; it does not automatically enforce behavior unless the compiler, runtime, or consuming framework recognizes and acts on it.
182. What Is a WeakReference? When Would You Want to Use One?
A WeakReference is a reference to an object that does not, by itself, prevent the garbage collector (GC) from collecting that object.
Normally, a strong reference keeps an object reachable. A weak reference allows the object to be collected when no strong references keep it alive.
Example
using System;
class Program
{
static void Main()
{
var data = new byte[1024];
var weakReference = new WeakReference(data);
Console.WriteLine(weakReference.IsAlive);
data = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Console.WriteLine(weakReference.IsAlive);
}
}
The object may become eligible for collection after the strong reference is removed. Garbage collection is not guaranteed to occur at a particular time, so weak-reference behavior should not be used to predict exact collection timing.
When Should You Use WeakReference?
- When maintaining a cache that should not keep objects alive unnecessarily.
- When tracking objects without extending their lifetime.
- When managing certain memory-sensitive object relationships.
Important: Do not use weak references as a replacement for proper resource management or as a general solution to memory leaks. Use a WeakReference<T> when a typed weak reference is appropriate.
183. What Is Strong Typing Versus Weak Typing? Which Is Preferred and Why?
Strong typing means that a programming language or its type system enforces restrictions on how values of different types can be used. Invalid operations are rejected unless an appropriate conversion or other permitted mechanism is used.
Weak typing is an informal term for languages or situations where types are converted or interpreted more permissively. The exact meaning depends on the language; it is not a single, universally defined category.
Example in C#
int number = 10;
string text = "20";
// This does not compile:
// int result = number + text;
// Explicit conversion is required:
int converted = number + int.Parse(text);
Comparison
| Feature | Strongly Typed Approach | More Permissive Typing |
|---|---|---|
| Type checking | Restricts invalid operations | May permit more implicit conversions |
| Error detection | Many errors can be caught at compile time | Some errors may appear at runtime |
| Maintainability | Types communicate intended usage | Conversions may make behavior less obvious |
| Flexibility | May require explicit conversions | Can allow more flexible operations |
Which is preferred?
For most business applications, strong typing is preferred because it improves compile-time error detection, readability, refactoring, and maintainability. C# is a statically typed language with several features that allow controlled dynamic behavior when needed.
184. What Is the Use of the using Keyword?
The C# using keyword has several uses. The two common ones are resource management and importing namespaces.
A. Resource Management
A using statement or declaration ensures that an object implementing IDisposable is disposed of when execution leaves its scope, including when an exception occurs.
using System.IO;
using (StreamReader reader = new StreamReader("data.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
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.
B. Namespace Import
The using directive allows types in a namespace to be referenced without writing the full namespace name each time.
using System;
Console.WriteLine("Hello World");
Without the directive, you could write:
System.Console.WriteLine("Hello World");
C. Namespace Alias
using IO = System.IO;
IO.File.ReadAllText("data.txt");
Summary: The using statement manages disposable resources, while the using directive imports namespace names. C# also supports using aliases and using directives for static members.
185. Explain the Difference Between Array, ArrayList, and List
An array, ArrayList, and List<T> are collection types that store multiple items, but they differ in size management and type safety.
| Feature | Array | ArrayList | List<T> |
|---|---|---|---|
| Namespace | System | System.Collections | System.Collections.Generic |
| Size | Fixed after creation | Grows or shrinks automatically | Grows or shrinks automatically |
| Type safety | Elements have a declared element type | Stores elements as object | Stores elements of the specified type |
| Value types | Stored directly as array elements | Typically boxed when stored as object | Stored as typed elements without boxing for ordinary value-type T |
| Performance | Efficient for fixed-size collections | May incur boxing and unboxing overhead | Generally preferred for resizable, typed collections |
Array Example
int[] numbers = { 10, 20, 30 };
Console.WriteLine(numbers[0]);
ArrayList Example
using System.Collections;
ArrayList items = new ArrayList();
items.Add(10);
items.Add("Hello");
int number = (int)items[0];
An ArrayList allows mixed types, but this can cause runtime errors and requires casts.
List<T> Example
using System.Collections.Generic;
List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(20);
int number = numbers[0];
Recommendation: Use arrays when the number of elements is fixed or array semantics are appropriate. Use List<T> for most resizable collections in modern C#. ArrayList is a legacy non-generic collection and is rarely preferred in new code.
186. What Is Memory Management in the CLR?
The Common Language Runtime (CLR) manages the execution of .NET applications, including managed memory allocation and garbage collection.
How CLR Memory Management Works
- Allocation: Objects are generally allocated on the managed heap. Many small allocations are handled efficiently by advancing an allocation pointer.
- Tracking: The garbage collector identifies object references and determines which objects remain reachable.
- Collection: Memory occupied by unreachable managed objects becomes available for reuse.
- Compaction: The GC may move objects to reduce fragmentation and update references.
- Finalization: Objects with finalizers may require additional processing before their memory can be reclaimed.
Generations
- Generation 0: Primarily short-lived objects.
- Generation 1: An intermediate generation for surviving objects.
- Generation 2: Longer-lived objects and objects that survive multiple collections.
The GC also manages the Large Object Heap for large allocations. Exact collection behavior depends on the runtime and workload.
Managed and Unmanaged Resources
Managed objects are tracked by the CLR garbage collector. Unmanaged resources, such as native operating-system handles, may need explicit cleanup through IDisposable and sometimes a finalizer as a fallback.
using var stream = new FileStream(
"data.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite);
The using declaration ensures that the stream is disposed of at the end of its scope.
Important: Garbage collection does not guarantee immediate memory reclamation or immediate return of memory to the operating system.
187. What Is the Difference Between var and dynamic?
var and dynamic may look similar, but they work differently.
| Feature | var | dynamic |
|---|---|---|
| Type determination | Determined by the compiler at declaration | Operations are generally resolved at runtime |
| Static typing | Yes | Member access and many operations bypass compile-time member checking |
| Compile-time errors | Many invalid operations are detected at compile time | Some invalid operations fail at runtime |
| Type changes | The variable's inferred type does not change | The variable can hold values of different runtime types |
Example of var
var number = 10;
// Compile-time type is int.
number = 20;
// This does not compile:
// number = "Hello";
Example of dynamic
dynamic value = 10;
Console.WriteLine(value);
value = "Hello";
Console.WriteLine(value);
// This compiles but fails at runtime:
// value.NonExistingMethod();
When to use: Use var when the type is clear from the expression or when the compiler requires it, such as for anonymous types. Use dynamic only when runtime binding is genuinely useful, such as certain COM interoperability scenarios or dynamic data integration.
188. Name at Least Three Component Containers That Ship with the Windows Server Family
A component container provides an environment in which components can be hosted, managed, activated, or accessed by clients.
Examples associated with the classic Windows Server and .NET Framework ecosystem include:
- COM+ Services: Provides a component infrastructure with services such as transactions, object pooling, and role-based security for supported components.
- Internet Information Services (IIS): Hosts web applications and web services. Classic IIS can host ASP.NET applications in worker processes.
- Windows Services / Service Control Manager: Supports long-running background processes that can host application components and services.
- Microsoft Transaction Server (MTS): A historical component-hosting and transaction-management technology that preceded COM+ and was integrated into later Windows component infrastructure.
Interview note: The exact expected answer depends on the historical Windows Server version and the meaning of “component container” intended by the interviewer. COM+, IIS, and Windows Services are useful examples of hosting environments, but they are not interchangeable technologies.
189. Explain the Memory Allocation of Value Types and Reference Types
C# distinguishes value types and reference types by their copying and storage semantics. It is not strictly correct to say that every value type lives on the stack and every reference type lives on the heap.
Value Types
Value types include int, double, bool, struct, and enum.
A value-type variable contains its value directly. Where that value is stored depends on its context.
int a = 10;
int b = a;
b = 20;
Console.WriteLine(a); // 10
Console.WriteLine(b); // 20
Changing b does not change a because the assignment copies the value.
Reference Types
Reference types include classes, arrays, delegates, and strings. A reference-type variable holds a reference to an object, rather than containing the entire object inline.
class Person
{
public string Name { get; set; }
}
Person p1 = new Person { Name = "Ravi" };
Person p2 = p1;
p2.Name = "Arun";
Console.WriteLine(p1.Name); // Arun
Both variables refer to the same object, so modifying the object's property through one reference is visible through the other.
Where Is Memory Allocated?
- Local variables may be held in registers, stack locations, or optimized away.
- Value-type fields inside a class are stored as part of that class object's memory.
- Value types stored inside arrays are stored as array elements.
- Objects created with
neware generally allocated on the managed heap, although runtime optimizations can affect physical allocation. - Reference variables hold references to objects; the location of the reference itself depends on its context.
Key takeaway: The essential distinction is value-copying versus reference-sharing, not simply stack versus heap.
190. What Are the ref and out Keywords?
ref and out allow a method to receive a variable by reference so that the method can read or modify the caller's variable.
ref Keyword
The variable must be definitely assigned before it is passed using ref. The method can read and modify its current value.
static void Increment(ref int number)
{
number++;
}
int value = 10;
Increment(ref value);
Console.WriteLine(value); // 11
out Keyword
The method must assign an out parameter before returning normally. The caller does not need to initialize the variable before passing it.
static bool TryGetNumber(out int number)
{
number = 100;
return true;
}
if (TryGetNumber(out int result))
{
Console.WriteLine(result); // 100
}
Comparison
| Feature | ref | out |
|---|---|---|
| Caller initializes variable first | Required | Not required |
| Method can read initial value | Yes | No; it must assign the parameter before reading it |
| Method must assign before returning | No, not merely because it is ref | Yes, on every normal return path |
| Typical use | Modify an existing value | Return an additional result through a parameter |
Important: The caller must use the same keyword in the call as required by the method signature. These keywords do not make reference-type objects immutable or automatically make code thread-safe.
| C# Sharp QA-18 :👈 | 👉:C# Sharp QA-20 |