| C# Sharp QA-17 :👈 | 👉:C# Sharp QA-19 |
C# (C-Sharp) Question Answers - 171-180 |
171. What Is the Difference Between a Debug and Release Build? Is There a Significant Speed Difference?
Debug builds are intended to make debugging easier. Release builds are intended for deployment and production use.
| Feature | Debug | Release |
|---|---|---|
| Optimization | Usually reduced or disabled, depending on project settings. | Usually enabled. |
| Debugging | Designed to support stepping and inspection. | Debugging is possible with suitable symbols, but optimized code can be harder to inspect. |
| Code generation | May preserve more straightforward mappings to source code. | May inline methods, eliminate redundant work, and optimize execution. |
| Typical use | Development and troubleshooting. | Testing and production deployment. |
Is there a significant speed difference?
There can be. Release builds may run substantially faster for CPU-intensive workloads because of compiler optimizations. However, the difference depends on the application, its bottlenecks, runtime settings, and workload. A database-bound application might show little difference.
Modern .NET also uses JIT optimizations and may employ tiered compilation, so the final performance depends on both build configuration and runtime behavior. Benchmark the actual application instead of assuming a fixed speed improvement.
172. Does JITting Occur Per-Assembly or Per-Method? How Does This Affect the Working Set?
In traditional JIT compilation, managed methods are compiled to native machine code when execution requires them, rather than compiling every method in an assembly at once.
How It Works
- The CLR loads the required assembly and its metadata.
- When a method needs to execute, the runtime may compile its IL (Intermediate Language) into native machine code.
- The compiled code is reused for subsequent calls while it remains available.
- Runtime optimizations, including tiered compilation, may compile frequently executed methods again using more optimized code.
Effect on the working set:
- Only loading and executing the required parts can avoid the immediate cost of compiling every method.
- Native code generated by the JIT consumes memory.
- Loading additional assemblies, metadata, and methods can increase memory usage.
- Shared framework code and runtime implementation details affect actual memory consumption.
This is a general model, not an absolute rule: ahead-of-time compilation, ReadyToRun images, Native AOT, and other runtime features can change when and how native code is produced.
173. What's Wrong with a Line Like This? DateTime.Parse(myString);
DateTime.Parse(myString);
The problem is not that DateTime.Parse() is always wrong. The concern is that it can throw an exception or interpret a date differently depending on the input and culture.
Potential problems include:
- The string may be null, empty, or invalid.
- The input format may be ambiguous, such as
01/02/2026. - The current culture may interpret the date differently.
- Untrusted or unexpected input may cause a
FormatException.
Safer Option for User Input
if (DateTime.TryParse(myString, out DateTime date))
{
Console.WriteLine(date);
}
else
{
Console.WriteLine("Invalid date.");
}
For a Known Format
using System.Globalization;
bool success = DateTime.TryParseExact(
myString,
"yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime date);
Use TryParse() for flexible input and TryParseExact() when the input must follow a specific format. For timestamps that represent an instant across time zones, consider DateTimeOffset.
174. Write a Standard lock() Plus Double Check to Create a Critical Section Around a Variable Access
Double-checked locking checks whether an object has already been initialized before and after acquiring a lock. This avoids taking the lock on every access after initialization.
Thread-Safe Example
public sealed class MyService
{
private static readonly object _lock = new object();
private static volatile MyService _instance;
private MyService()
{
}
public static MyService Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = new MyService();
}
}
}
return _instance;
}
}
}
Why two checks?
- The first check avoids locking when the instance already exists.
- The lock allows only one thread at a time to enter the initialization section.
- The second check prevents another thread from creating a duplicate instance after waiting for the lock.
- The volatile field helps ensure appropriate visibility and ordering for this reference-based pattern.
Modern recommendation: Prefer Lazy<T> for ordinary lazy singleton initialization unless you have a specific reason to implement double-checked locking yourself.
private static readonly Lazy<MyService> _instance =
new Lazy<MyService>(() => new MyService());
public static MyService Instance => _instance.Value;
Also, a lock only protects accesses that follow the same synchronization strategy. Every relevant read and write to shared mutable state must be designed for thread safety.
175. What Benefit Does Your Code Receive If You Decorate It with Attributes Demanding Specific Security Permissions?
In the .NET Framework Code Access Security (CAS) model, declarative security attributes could specify permissions required by an assembly, class, or method.
For example, older .NET Framework code could use declarative security attributes to request or demand a permission before an operation was performed.
Potential benefits in the legacy CAS model:
- Make security requirements explicit.
- Allow permission checks to occur at defined boundaries.
- Support least-privilege design and earlier detection of insufficient permissions.
Important modern .NET distinction: The legacy CAS sandbox and permission-demand model is obsolete or unsupported in modern .NET. Adding such attributes does not automatically sandbox code or secure an application today.
Modern applications should use operating-system permissions, process isolation, least-privilege identities, appropriate authorization checks, and other supported security mechanisms.
176. What Does This Do? gacutil /l | find /i "Corillian"
gacutil /l | find /i "Corillian"
This command searches the Global Assembly Cache listing for lines containing the text Corillian, ignoring case.
gacutil /llists assemblies in the GAC on systems where the applicable .NET Framework tool is installed.|pipes the command output to another command.find /i "Corillian"displays lines containing the search text, regardless of letter case.
This is useful for checking whether a matching assembly appears in the GAC listing. It does not prove that an application successfully loads or uses that assembly.
Note: GAC tooling applies to the traditional .NET Framework and is not the normal assembly deployment model for modern .NET.
177. What Does This Do? sn -t foo.dll
sn -t foo.dll
The Strong Name tool's -t option displays the public key token associated with the public key in the specified file, where the file contains the appropriate strong-name public-key information.
A public key token is a short identifier derived from a strong-name public key. It is commonly used as part of an assembly's identity in .NET Framework.
Important distinction:
- A strong name identifies an assembly; it does not guarantee that the assembly is safe.
- The
-Toption is commonly used to display the public key token of a signed assembly. - Strong-name signing is different from Authenticode signing and publisher identity verification.
178. What Ports Must Be Open for DCOM over a Firewall? What Is the Purpose of Port 135?
DCOM (Distributed Component Object Model) uses RPC (Remote Procedure Call) infrastructure to allow components to communicate across machines.
TCP port 135 is used by the RPC Endpoint Mapper. A client contacts this service to discover the endpoint associated with a requested RPC interface.
After endpoint discovery, the client may need to communicate with the server using additional RPC ports.
| Port or range | Purpose |
|---|---|
| TCP 135 | RPC Endpoint Mapper for endpoint discovery. |
| Dynamic RPC ports | Carry subsequent RPC/DCOM communication. The range depends on Windows version and configuration. |
Modern Windows installations commonly use the dynamic TCP port range 49152-65535 by default, although configuration and operating-system version can change the effective range. Older Windows systems used different ranges.
Firewall guidance: Configure the required RPC/DCOM endpoints and firewall rules for the actual environment. Where supported, restricting the dynamic RPC range or configuring a suitable fixed endpoint can reduce the number of required open ports. Do not assume that opening port 135 alone is sufficient.
179. How Does the XmlSerializer Work? What ACL Permissions Does a Process Using It Require?
XmlSerializer converts .NET objects to XML and XML data back into .NET objects. It is commonly used for XML-based data exchange and serialization.
Serialization Example
using System.IO;
using System.Xml.Serialization;
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
var serializer = new XmlSerializer(typeof(Employee));
var employee = new Employee
{
Id = 1,
Name = "Ravi"
};
using var writer = new StringWriter();
serializer.Serialize(writer, employee);
string xml = writer.ToString();
How It Works
- It examines the target type and its public serialization members.
- It determines how the object's data maps to XML elements and attributes.
- It uses generated serialization code or an available pre-generated serializer where supported.
- It reads or writes XML using the configured mappings.
What ACL Permissions Are Required?
ACL means Access Control List. The permissions required depend on the runtime, hosting environment, serializer configuration, and whether generated serialization code is used.
- The process needs the appropriate permissions to read input files and write output files, if files are involved.
- Some .NET Framework serializer scenarios generate temporary source or assembly files and may require appropriate access to the configured temporary directory.
- Pre-generated serialization assemblies can avoid some runtime generation work.
- Modern .NET implementations differ from legacy .NET Framework behavior, so temporary-file and dynamic-code requirements should be verified for the target runtime.
Security best practice: Do not grant broad filesystem permissions or FullTrust merely because an application uses XmlSerializer. Grant only the permissions that the particular application and runtime actually require.
180. What Is the Significance of the PropertySpecified Pattern Used by XmlSerializer? What Problem Does It Attempt to Solve?
The PropertySpecified pattern allows XML serialization to distinguish between a property that has a value and a property that was explicitly supplied or should be included in the serialized XML.
This is particularly useful when the XML contract distinguishes between an omitted element and an element explicitly containing a default value, such as 0 or false.
Example
using System.Xml.Serialization;
public class Product
{
public int Quantity { get; set; }
[XmlIgnore]
public bool QuantitySpecified { get; set; }
}
When the corresponding convention is recognized by XmlSerializer, QuantitySpecified controls whether Quantity is serialized. During deserialization, it can indicate whether the corresponding XML element was present.
For example, an XML document might omit the quantity entirely, while another might explicitly contain <Quantity>0</Quantity>. Without an additional presence indicator, both cases could otherwise result in the same default integer value of zero.
Important: The companion property must follow the serializer's naming and type conventions. It is commonly a Boolean property named after the serialized member with the suffix Specified, and it is typically excluded from XML using [XmlIgnore].
| C# Sharp QA-17 :👈 | 👉:C# Sharp QA-19 |