This interview guide is for educational and informational purposes only. It is designed to help readers prepare, but it does not guarantee any interview result, hiring decision, offer, or outcome. Interview questions, hiring criteria, and preferred answers can vary by employer, interviewer, industry, location, and time. The examples and explanations reflect the authors' research and judgment, are provided without warranties of any kind, and should not be treated as the only correct approach. Diagrams are simplified illustrations intended to highlight the main components and their interactions; actual systems and implementations may be more complex. Alternative approaches may be equally valid or better suited to a particular question, context, or interviewer. To the fullest extent permitted by applicable law, the author, contributors, and publisher are not liable for decisions made, actions taken, or losses incurred based on this guide.
Identity, Image, and Privacy Notice
To respect individual privacy, some names, profile photographs, avatars, biographical details, and other identifying information displayed in this guide may be replaced with pseudonyms, licensed stock images, illustrative avatars, composite images, or representative descriptions. Unless a person is expressly identified as an actual contributor, a displayed name, image, or profile should not be understood as depicting or identifying a specific candidate, interviewer, employee, or other real individual. These representations are provided for editorial and illustrative purposes only and do not imply endorsement, employment, participation, or affiliation with this guide or any company mentioned in it. Any resemblance to an actual person is coincidental.
Company Notice
This guide is an independent educational resource and is not affiliated with, endorsed by, sponsored by, or approved by the company named in this guide. Company names are used only to identify interview experiences commonly reported by candidates. Interview practices can change without notice, and inclusion of company-specific content does not mean these questions are official, complete, or guaranteed to be asked. To the fullest extent permitted by law, the author, contributors, and publisher are not responsible for outcomes related to use of this material.
Questions or comments?
Contact us for general questions, or share feedback, technical corrections, and comments with the community.
11. What is the difference between var, dynamic, and explicit typing?Language SpecificEasy
i Question Details
Explain What is the difference between var, dynamic, and explicit typing in C# with a simple example, common mistakes, and when it matters in production.
Short Interview Answer (30-60 seconds)
Explicit typing is the clearest choice. var lets the compiler infer the type at compile time, so the value is still strongly typed. dynamic skips compile time member checks and waits until runtime, so it is more flexible but less safe.
At a simple level, this question asks how C# chooses the type of a value. With explicit typing, I write the type myself. With var, the compiler figures out the type from the right side at compile time, but the type is still fixed. With dynamic, the compiler does not check the member access until runtime. So var is still strongly typed, while dynamic delays checks until the app runs. The choice matters for readability, safety, and errors you want to catch early.
Useful Questions to Ask the Interviewer
Are we using this in a normal app or a library?
Do we need runtime flexibility from COM, JSON, or scripting?
How to Explain It in an Interview
In C#, explicit typing means I write the type, like int count = 10. var means the compiler infers the type from the initializer, so var count = 10 is still an int. The type is known at compile time and cannot change later. dynamic is different. It skips compile time member checking and asks the runtime to resolve members and operations. For example, dynamic value = "abc"; value.Length works, but value.NoSuchMember throws only when the code runs.
So var is for reducing noise when the type is obvious, especially with LINQ or anonymous types. Explicit typing is best when the type improves clarity, public APIs, or maintenance. dynamic is for rare cases where the real type is not known until runtime, such as COM interop, some reflection heavy code, or code that talks to flexible objects.
In production, I prefer explicit typing first, var second, and dynamic only when there is a real runtime need. var has no runtime penalty because it is just compile time inference. dynamic adds runtime binding cost and removes compile time safety, so mistakes show up later. The main rule is simple: var keeps strong typing, dynamic does not.
Code
using System;
using Microsoft.CSharp.RuntimeBinder;
publicstaticclassProgram
{
publicstaticvoidMain()
{
// var uses compile time type inference, so count becomes int.var count = 10;
// Explicit typing says the same thing directly.int explicitCount = 10;
// dynamic defers member checking until runtime.dynamic text = "hello";
Console.WriteLine($"var count type: {count.GetType().Name}");
Console.WriteLine($"explicitCount type: {explicitCount.GetType().Name}");
Console.WriteLine($"dynamic text length: {text.Length}");
try
{
// This compiles, but fails only when the program runs.
Console.WriteLine(text.NotARealMember);
}
catch (RuntimeBinderException ex)
{
Console.WriteLine($"dynamic failed at runtime: {ex.GetType().Name}");
}
}
}
Why Interviewers Ask This
Interviewers ask this to check whether I understand how C# chooses types, when checks happen, and when to use compile time safety instead of runtime flexibility.
Common interview mistakes
A common mistake is thinking var means weak typing or dynamic. It does not. The compiler still knows the exact inferred type. Another mistake is using dynamic for normal code just to write less syntax. That hides errors until runtime and makes maintenance harder.
Interview tip
Say var is compile time inference, dynamic is runtime binding, and explicit typing is best when the type helps readers understand the code quickly.
Interviewer may ask next
Can var be used with null?
No. The compiler needs a real initializer type, so var value = null does not work unless the right side gives a type. That matters because var is inference, not a placeholder for any type.
Is dynamic slower than var or explicit typing?
Yes. dynamic adds runtime binding cost because member lookup happens when the app runs. That matters in hot code paths and repeated calls. The tradeoff is flexibility versus speed and compile time safety.
12. What are nullable value types in C#?Language SpecificHard
i Question Details
Cover how nullability is represented for value types and why it matters when a number or date may be absent.
Short Interview Answer (30-60 seconds)
Nullable value types let a C# value type such as int, decimal, or DateTime represent either a normal value or no value. I write int? as shorthand for Nullable<int>. I normally test for null, use pattern matching, check HasValue, or use operators such as ?? before I depend on the contained value. This is useful when zero, false, or a default date could be a valid value and therefore should not mean missing.
Sometimes an application needs to show that a number, date, or true or false value is missing. Using zero, false, or an ordinary date value to mean missing can be wrong because each may also be real data. C# lets these kinds of values represent either a real value or nothing. For example, an optional age can contain 35 or contain no age. This keeps missing information separate from normal values and makes the meaning of stored or received data clearer.
Useful Questions to Ask the Interviewer
Do you want me to explain how nullable values are represented internally?
Should I also cover operator behavior and boxing?
How to Explain It in an Interview
A nullable value type is represented by System.Nullable<T>. The type argument T must be a value type that is not itself nullable. C# provides shorter syntax, so int? means Nullable<int> and DateTime? means Nullable<DateTime>.
Nullable<T> has two important properties. HasValue reports whether a value is present. Value returns the contained value when one is present. Reading Value when HasValue is false throws InvalidOperationException. GetValueOrDefault returns the contained value when present. Otherwise, it returns the default value of T. In normal code, a null test, pattern matching, ??, or GetValueOrDefault can make the intended behavior clearer than reading Value directly.
Nullable value types matter because a default value is not the same as missing data. Zero can be a valid integer. False can be a valid Boolean result. A DateTime can also contain its default value. Using int?, bool?, or DateTime? lets the program represent absence without reserving one ordinary value as a special marker.
Many operators that work on value types have lifted forms for nullable operands. For arithmetic such as nullable integer addition, if an operand is null, the result is null. Nullable comparisons follow their defined C# rules, so null must not be treated as if it were an ordinary number.
Nullable<T> is still a value type. Assigning it to another variable copies its state. It does not require a separate managed heap object merely because it is nullable. Its storage includes the underlying value and state that records whether a value is present, with exact size and padding depending on the type and runtime layout.
Boxing has special behavior. If a nullable value has a value, boxing produces a boxed instance of the underlying T value. If it has no value, boxing produces a null reference.
In production, nullable value types are useful for optional database values, dates, measurements, identifiers, and other business data where absence is different from an ordinary default value.
Code
using System;
publicstaticclassProgram
{
publicstaticvoidMain()
{
// int? is shorthand for Nullable<int> and can contain an integer or no value.int? ageWithValue = 35;
int? missingAge = null;
// Check that a value exists before reading Value directly.if (ageWithValue.HasValue)
{
Console.WriteLine(ageWithValue.Value);
}
// No value is present, so this returns the default integer value, which is zero.
Console.WriteLine(missingAge.GetValueOrDefault());
// Provide an explicit fallback value when the nullable integer is null.int displayedAge = missingAge ?? 18;
Console.WriteLine(displayedAge);
// A nullable integer with a value boxes as the underlying Int32 value.object? boxedValue = ageWithValue;
Console.WriteLine(boxedValue?.GetType().Name);
// A nullable integer with no value boxes to a null reference.object? boxedMissing = missingAge;
Console.WriteLine(boxedMissing isnull);
}
}
Why Interviewers Ask This
Interviewers ask this to check whether a candidate understands how C# represents an optional value such as a number or date. They also want to see whether the candidate understands Nullable<T>, the T? syntax, safe value access, operator behavior, boxing, memory use, and the difference between an absent value and a real default value.
Common interview mistakes
A common mistake is using the default value of a value type to mean missing. Zero, false, and a default DateTime can all be legitimate values. Another mistake is reading Value without first knowing that a value exists, which can throw InvalidOperationException. Developers may also assume Nullable<T> is a reference type because it can represent no value, but Nullable<T> is a value type. Another mistake is assuming boxing preserves Nullable<T> as the boxed runtime type. A nullable value with data boxes as its underlying value type, while a nullable value without data boxes to null.
Interview tip
Start by saying that T? lets a value type represent either a real value or no value. Then explain that it is shorthand for Nullable<T>. Use a simple example such as int? age, explain safe access, and finish with the practical reason: an ordinary default value may be valid data and should not automatically mean missing.
Interviewer may ask next
What happens if you access Value when a nullable value type contains no value?
It throws InvalidOperationException. Nullable<T>.Value can only be read safely when HasValue is true. This matters because ordinary missing data can otherwise cause a runtime failure. Depending on the required behavior, production code can use a null test, pattern matching, GetValueOrDefault, or ?? instead of reading Value without a prior check.
What happens when a nullable value type is boxed?
Boxing has special nullable behavior. If the nullable value contains a value, the CLR boxes the underlying T value rather than Nullable<T>. If the nullable value contains no value, the result is a null reference. This matters when nullable values pass through APIs that use object because the observed runtime value is either the boxed underlying value type or null.
13. What is the difference between static and instance members?Language SpecificEasy
i Question Details
Explain What is the difference between static and instance members in C# with a simple example, common mistakes, and when it matters in production.
Short Interview Answer (30-60 seconds)
Static members belong to the type and are shared. Instance members belong to each object and can hold separate state. I use static for shared helper logic or shared data, and instance members when each object needs its own values.
Detailed Explanation
This question asks whether a value belongs to the whole type or to one created object. A shared value is the same for every object. A private value belongs to only one object, so it can be different each time. That choice matters because shared data behaves the same for everyone, while per object data can change from one object to another. In C#, that affects design, state, and how you avoid bugs in code that runs many times.
Useful Questions to Ask the Interviewer
Should this value be shared by every object?
Should each object keep its own copy?
How to Explain It in an Interview
Static members belong to the type itself. You can use them without creating an object. Instance members belong to one specific object, so you must create that object first. In C#, a static method or static property can only use other static members directly, because it does not have a current object to work with.
This difference matters in design. Use static for logic that does not depend on one object, such as a helper method, a shared lookup, or a factory method. Use instance members when the data changes from object to object, such as a user name, an account balance, or request data. Static mutable state can be risky in production because every thread and every request sees the same data. That can create hidden bugs and make tests harder to trust. Instance state is easier to reason about when each object should stay independent.
A simple rule is this. If the value belongs to the type, make it static. If the value belongs to one object, make it an instance member.
Why Interviewers Ask This
Interviewers want to see whether you know what is shared by the type and what lives in each object. They are checking if you understand how that choice affects state, memory, and safe use in real code.
Common interview mistakes
A common mistake is to use static for data that should be different for each object. Another mistake is to assume a static method can read instance members directly. It cannot, because there is no current object. People also forget that static mutable fields are shared, so one change can affect every caller. That can make tests flaky and production bugs hard to trace.
Interview tip
Say that static means one shared copy for the type, while instance means one copy per object. Then give one real example of each and mention the shared state risk.
Interviewer may ask next
Can a static method access instance members?
No. A static method cannot access instance members directly because it has no current object. It can only use static members, or it must receive an object first. This matters because the method is tied to the type, not to one object.
When should I prefer instance members over static members in production?
Prefer instance members when the data belongs to one object or can change per request, per user, or per operation. This reduces shared state and makes the code easier to test. The main tradeoff is that you must create and pass the object around, but that usually gives safer design.
14. What is the difference between const and readonly?Language SpecificEasy
i Question Details
Focus on compile-time versus runtime initialization, where each can be assigned, and what happens in a class versus an object.
Short Interview Answer (30-60 seconds)
Use const when the value is known at compile time and is truly fixed. Use readonly when the value should not be reassigned after initialization but must be chosen at runtime. A const field is implicitly static, so one constant belongs to the type. An instance readonly field belongs to each object and can receive a different value in that object's constructor.
Use const when a value is completely fixed before the program runs and can be written as a C# constant. Use readonly when the value must stay fixed after setup but can be decided while the program is running. For example, a fixed retry count that is part of the program definition can be const. A name supplied when an object is created can be readonly. This matters because const gives one type level value known during compilation, while an instance readonly field lets every object keep its own value after construction.
Useful Questions to Ask the Interviewer
Should I explain both instance readonly fields and static readonly fields?
Would you like me to cover the versioning difference caused by const values being copied into compiled calling code?
How to Explain It in an Interview
In C#, const means the value must be a compile time constant. A const field must be assigned where it is declared. It is implicitly static, so it belongs to the type rather than to each object. Code that uses a const value normally has that value placed into the compiled calling code. This matters when a public constant is changed in a library because existing callers may need to be recompiled before they use the new value.
readonly is different because its value can be established at runtime. An instance readonly field can be assigned where it is declared or inside an instance constructor of the same class. Different objects can therefore receive different values. After construction, normal code cannot assign another value to that field.
A static readonly field also belongs to the type, but its value can be created at runtime. It can be assigned where it is declared or inside the static constructor of the same class.
const supports only types and values that C# allows as constants. readonly fields can use normal field types, including reference types and values created at runtime. readonly restricts assignment to the field itself. If a readonly field stores a reference to a mutable object, the object can still change internally because the field continues to hold the same reference.
In production code, const is best for values that are genuinely permanent parts of the program definition. readonly is safer when initialization depends on runtime information or when a shared library value may change between releases. Neither choice creates a meaningful asymptotic performance or memory complexity difference for this question.
Code
using System;
publicstaticclassProgram
{
publicstaticvoidMain()
{
// Each object receives its own readonly Name value during construction.var first = new AppSettings("Production");
var second = new AppSettings("Testing");
Console.WriteLine(AppSettings.MaxRetries);
Console.WriteLine(first.Name);
Console.WriteLine(second.Name);
Console.WriteLine(AppSettings.StartedAt);
}
}
publicsealedclassAppSettings
{
// This constant is known during compilation and belongs to the type.publicconstint MaxRetries = 3;
// Each object can receive a different value during its construction.publicreadonlystring Name;
// One value is shared by the type, but it is created at runtime.publicstaticreadonly DateTime StartedAt;
staticAppSettings()
{
// The static constructor is an allowed place to assign this static readonly field.
StartedAt = DateTime.UtcNow;
}
publicAppSettings(string name)
{
// The instance constructor is an allowed place to assign this instance readonly field.
Name = name;
}
}
Why Interviewers Ask This
Interviewers ask this to check whether the candidate understands when C# fixes a value, where each kind of field may be assigned, and whether the value belongs to the type or to each object. It also tests whether the candidate can choose correctly between a value known during compilation and a value that must be established while the program is running.
Common interview mistakes
A common mistake is saying that const and readonly are equivalent because both prevent normal later assignment. const requires a compile time constant value, while readonly can be initialized at runtime. Another mistake is assuming every readonly field is shared by all objects. Only static readonly is shared by the type. An instance readonly field belongs to each object. Candidates also sometimes think readonly makes a referenced object immutable. It does not. It prevents replacing the field value after allowed initialization, but a mutable referenced object can still change internally. Another mistake is forgetting that changing a public const value may require callers to be recompiled before they observe the new value.
Interview tip
Start with the initialization timing. Say that const is fixed at compile time, while readonly can be set at runtime during allowed initialization. Then explain that const is implicitly static, while an instance readonly field can differ for each object. Finish by mentioning static readonly and the public const versioning concern if the interviewer wants more depth.
Interviewer may ask next
If a readonly field refers to a mutable object, can that object's contents still change?
Yes. readonly prevents the field from being assigned a different reference after its allowed initialization, but it does not make the referenced object immutable. For example, if a readonly field refers to a List<int>, code can still add items to that list. The field continues to refer to the same list while the list's internal state changes. This matters because readonly protects field assignment, not the complete state of the referenced object.
When would you choose static readonly instead of const?
Choose static readonly when one value should be shared by the type but must be determined at runtime, uses a type that cannot be a C# constant, or may change between library releases without relying on callers being recompiled. static readonly stores a field that callers read at runtime. const normally places the constant value into compiled calling code. The main tradeoff is that const gives true compile time constant semantics, while static readonly gives more flexible runtime initialization and safer versioning for values that may change.
15. What is a static class, and when should it be used?Language SpecificEasy
i Question Details
Describe the constraints on static classes and why they fit utility-style functionality without instance state.
Short Interview Answer (30-60 seconds)
A static class is a helper class you use by name, without creating an object first. It is best for code that always does the same kind of work, like formatting text, converting values, or checking rules. Because it does not hold per object data, it keeps the design simple and lowers the risk of accidental state bugs. In C#, you call its members through the class name, not through an instance.
Detailed Explanation
A static class is a helper class that you use by name, without creating an object first. It is a good fit when the code does one small job and does not need to remember anything between calls. For example, it can format text, convert values, or hold shared helper methods. It keeps the code simple because there is no per object data to manage. In C#, that also means less chance of accidental state bugs when many parts of the app call it.
Useful Questions to Ask the Interviewer
Is this code meant to stay stateless?
Do you need extension methods or shared helper methods here?
How to Explain It in an Interview
A static class is for behavior that belongs to the type itself, not to one object. In C#, you cannot create an instance of it. Every member must also be static. That makes the intent very clear. The code is just a shared helper, not something that stores its own separate data.
This is useful for pure helper work such as parsing, formatting, math, or small utility methods. It is also the required home for extension methods. Because there is no object to build, you avoid a small allocation for each use of the class itself.
Use a static class when the logic is stateless and shared by everyone. Do not use it for services that need dependency injection, per request data, or behavior that changes from one object to another. If the code needs state, a normal class is usually the better choice. Static mutable state can also make testing harder and can create thread safety problems.
Why Interviewers Ask This
They want to check that you know the C# rule for type level helper code and that you can tell when a class should stay stateless.
Common interview mistakes
A common mistake is using a static class for shared mutable state. That can make code harder to test and can create thread safety problems. Another mistake is expecting to inject a static class with dependency injection or to inherit from it. Some people also use static classes for code that really needs one object per request or per user, which is the wrong fit.
Interview tip
Start with the simplest rule: no object, no instance state, type level helper. Then give one good example and one reason not to use it for stateful code.
Interviewer may ask next
Can a static class have constructors?
Yes, it can have a static constructor, but not an instance constructor. A static constructor runs once before the class is first used, and it is often used to initialize static readonly data. That matters because it still does not create an object and it still cannot hold per object state.
What is the tradeoff of using static helper classes instead of normal classes?
The main tradeoff is simplicity versus flexibility. Static helpers are easy to call and have no object allocation, but they are harder to replace in tests and cannot use dependency injection. That matters when you need different behavior, per request state, or easier mocking.
16. What is a static constructor?Language SpecificEasy
i Question Details
Explain one-time type initialization, when the runtime runs it, and why it can be used for shared setup.
Short Interview Answer (30-60 seconds)
A static constructor runs once for a type before the type is used for the first time, and it is used to set up shared static data.
Detailed Explanation
This question asks about the special code that runs once for a type before anything uses it. It is not for a single object. It is for values that the whole type shares. In C#, you do not call it yourself. The runtime runs it automatically before the first use of the type. This matters when a class needs shared setup, like default values, a cache, or a helper that must be ready before any object is created or any static member is read.
Useful Questions to Ask the Interviewer
Do you want shared values only, or also shared resources?
Should I talk about runtime timing or language rules?
How to Explain It in an Interview
A static constructor runs one time for a type. It is used to set up shared static state. For example, a logger class can load a default prefix or build a shared lookup table. C# runs it automatically. You never call it directly. The runtime runs it before the first instance is created or before any static member is used. After that, it never runs again.
This behavior exists so shared setup is safe and predictable. The type gets a chance to initialize itself before code uses it. A static constructor cannot take parameters, so it cannot depend on per call data. It is also not a normal public method, so it is only for internal type initialization.
Use it for small, clear setup that belongs to the type itself. Do not use it for heavy work or slow I O unless you really want the first use of the type to wait. If the setup throws, the type can fail to load, so the error can block later use. That is why many teams keep static constructors short and simple.
Why Interviewers Ask This
They want to check that I know when C# runs type initialization, that it happens only once, and that I understand when shared setup is a good fit.
Common interview mistakes
Thinking it runs on every object, calling it by hand, putting slow work inside it, or using it for data that should change per call.
Interview tip
Say that it is automatic, runs once, and is best for shared setup that belongs to the type.
Interviewer may ask next
Can a static constructor take parameters?
No. A static constructor cannot take parameters. The runtime calls it automatically, so the setup must come from code inside the type.
What is the tradeoff of heavy work in a static constructor?
The tradeoff is that the first use of the type becomes slower, and a failure can stop the type from being used. That is why shared setup should stay small when possible.
17. What is a class and what is an object?Language SpecificEasy
i Question Details
Keep the answer on type definition versus instance creation, and include how state lives in an object.
Short Interview Answer (30-60 seconds)
A class is the blueprint in C#. An object is one real thing created from that blueprint. The object holds its own state, so each object can store different values even when it comes from the same class.
Detailed Explanation
A class is like a plan. It tells us what data a thing should keep and what actions it can do. An object is one real thing made from that plan. Each object keeps its own values, so two objects from the same plan can still be different. In C#, a bank account class can make many account objects, and each one can hold a different balance.
Useful Questions to Ask the Interviewer
Do you want a simple example from our codebase?
Do you use classes only for data, or also for behavior?
How to Explain It in an Interview
In C#, a class defines a type. It is the shape for a group of related data and methods. An object is one instance created from that class with new. That object lives in memory and has its own state, meaning the current values in its fields and properties. If you create two objects from the same class, each one can store different values. The class definition is shared, but the state belongs to each object.
This matters because C# code often passes around references to objects, not copies of the whole object. When you assign one object variable to another, you copy the reference, so both variables point to the same object. That is why a change through one reference can be seen through the other. In production, this is useful for models like customers, orders, and services where each item needs its own data.
Use a class when you need behavior and state together, or when different objects must keep separate values. Do not confuse the class definition with the live object. A common mistake is to think the class stores the data. In reality, the live data belongs to each object instance.
Why Interviewers Ask This
Interviewers ask this to check whether you understand the core building blocks of C# and can explain how a type definition becomes a live object with its own state.
Common interview mistakes
A common mistake is to say the class is the object. Another mistake is to think every object shares the same state. Another is to forget that assigning one class variable to another usually copies the reference, not the whole object. People also mix up class and record. A class is best when the object can change and has behavior.
Interview tip
Say this in one line first: class is the blueprint, object is the instance, and state lives in the object. Then add a small C# example if asked.
Interviewer may ask next
What happens if you assign one object variable to another?
The reference is copied, not the whole object. Both variables point to the same object, so a change through one is visible through the other. That matters because the state is shared until you create a new object or copy the values yourself.
When would you use a class instead of a record?
Use a class when the object has changing state, identity, or behavior that matters. A record is better for simple data that is mostly compared by value. The tradeoff is that a class gives more control over mutable state, while a record gives easier value style behavior.
18. What is the difference between class and struct?Language SpecificHard
i Question Details
Compare value semantics, copying, default initialization, and when a small immutable struct is a better fit than a class.
Short Interview Answer (30-60 seconds)
I use a class when the object has identity, may be shared, needs class inheritance, or is large and mutable. I use a struct for a small value that behaves as one complete value and is usually immutable. A class is a reference type, so assignment copies the reference and both variables can refer to the same object. A struct is a value type, so assignment copies the value. A struct also always has a default zero initialized value. Large or mutable structs can cause unnecessary copying or confusing behavior.
Detailed Explanation
A class and a struct both let you group related data and behavior in C#. The practical difference is what happens when values are assigned or passed around. With a class, two variables can refer to the same object, so a change through one reference can be seen through the other. With a struct, assignment copies the value, so each variable has its own struct value. This choice matters when deciding whether something should behave like a shared object with identity or like a small independent value such as a coordinate or measurement.
Useful Questions to Ask the Interviewer
Should this type have its own identity and be shared by different parts of the program?
Is this type expected to be a small immutable value?
How to Explain It in an Interview
A class is a reference type. A variable of a class type holds a reference to an object. Assigning that variable to another variable copies the reference. Both variables can therefore refer to the same object. If the object is mutable, a change made through one reference can be observed through the other reference.
A struct is a value type. Assigning one struct variable to another has value semantics, so the receiving variable gets its own struct value. The same rule applies to ordinary argument passing because C# passes arguments by value by default. For a class argument, the reference is copied. For a struct argument, the struct value is copied.
A struct copy is not automatically a deep copy. If a struct contains a reference type field, the reference is copied, so both struct values can still refer to the same referenced object.
Default initialization is another important difference. The default value of a class reference is null. The default value of a struct has all its fields set to their default values. A struct can declare a public parameterless constructor in modern C#, but default expressions and zero initialized storage still produce the default value without requiring that constructor to run.
A small immutable struct is a good choice when the type represents one value without separate identity. Coordinates and measurements are common examples. A readonly struct can help enforce that design. A class is usually better when the object has identity, is shared, is large, changes over time, or needs to inherit from another class. Structs cannot inherit from classes or other structs, although they can implement interfaces.
Large structs can make copying more expensive. Boxing a struct to object or to an interface when boxing is required can also create a managed object. Structs are not simply stack values. Their storage depends on context, such as whether they are local values, fields inside objects, or elements of arrays.
Why Interviewers Ask This
Interviewers ask this to check whether the candidate understands value types and reference types in C#. They want to see whether the candidate knows what is copied during assignment and ordinary argument passing, how default initialization works, and how mutation can create surprising results. They also want practical judgment about when a small immutable value is a better struct candidate and when object identity, sharing, inheritance, or a larger mutable object makes a class more appropriate.
Common interview mistakes
A common mistake is saying that structs always live on the stack and classes always live on the managed heap. Struct storage depends on context, and a struct can be stored as a field inside a managed object or as an element of an array. Another mistake is assuming that copying a struct performs a deep copy. Reference type fields inside the struct still refer to the same referenced objects after the struct is copied. Developers also sometimes create large mutable structs, which can cause unnecessary copying and surprising mutation behavior. Another mistake is assuming that a declared parameterless struct constructor always runs during default initialization. Default expressions and zero initialized storage still produce the default struct value.
Interview tip
Start with value semantics versus reference semantics. Explain that struct assignment copies the value while class assignment copies the reference. Then explain default initialization and shallow copying. Finish with the practical rule that a small immutable value without identity is a strong struct candidate, while a shared, large, mutable, or identity based object is usually better represented by a class.
Interviewer may ask next
What happens if a struct contains a reference type field and the struct is copied?
The struct gets a separate value, but the referenced object is not deeply copied. The reference field itself is copied, so both struct values can refer to the same object through that field. This is shallow copying behavior. It matters because modifying that referenced object can be visible through both struct values even though the struct values themselves are separate.
Why can a large struct be less suitable than a class in performance sensitive code?
A large struct can be less suitable because value semantics can require copying more data during assignment, ordinary argument passing, or returns, although the runtime and compiler may optimize some copies. A class normally copies only its reference in those operations. A struct can also require boxing in some object or interface based uses, which can create a managed object. The tradeoff is that a small struct provides useful value semantics and compact inline storage, while a class is often a better fit when copying a large value would be costly or the object needs identity and sharing.
19. What is a constructor?Language SpecificEasy
i Question Details
Explain object initialization, how constructors are selected, and what must already be true before the instance is usable.
Short Interview Answer (30-60 seconds)
A constructor is a special method that runs when I create a new object. It sets the object up with valid starting values, and C# chooses the constructor by matching the arguments I pass.
Detailed Explanation
This question asks about the special setup that runs when you make a new item in C#. It gives the item its first values, checks that needed input is valid, and makes sure the item starts in a safe state. That matters because later code should not use something that is only partly ready. The question also asks how C# picks the right one when more than one is available, and what must already be true before the item can be used.
Useful Questions to Ask the Interviewer
Do you want the answer for classes only, or for structs too?
Should I focus on overloads or object setup?
How to Explain It in an Interview
In C#, a constructor is a special method with the same name as the class. It has no return type. It runs when you create an object with new. Its job is to put the object into a valid starting state. That often means setting required fields, checking input, and wiring any needed dependencies.
C# selects a constructor by looking at the arguments you pass. If several constructors exist, the compiler picks the best match by parameter list. If there is no match, the code does not compile. A constructor can also call another constructor in the same class or the base class, so shared setup can live in one place.
The instance is usable only after the constructor and any base constructor finish. That matters because code should not see a half done object. In production, constructors are best for required setup that must always happen. They are not a good place for slow work, network calls, or logic that often fails. Keeping them small makes objects easier to create, test, and trust.
Why Interviewers Ask This
Interviewers ask this to see whether you understand how object creation works in C#, how overloaded constructors are selected, and why an object must be fully initialized before code uses it.
Common interview mistakes
A common mistake is thinking a constructor can return a value or be called like a normal method. Another is assuming C# picks one by name only. It picks by parameter list. People also forget that the object should not expose invalid state after construction. Another mistake is putting heavy work in a constructor, which makes object creation slow and hard to test.
Interview tip
Say that a constructor prepares the object, C# selects it by arguments, and the object is ready only after construction finishes.
Interviewer may ask next
What happens if one constructor calls another?
The called constructor runs first, and the object is still not ready until the full chain, including the base constructor, has finished. This matters because shared setup can live in one place. The main tradeoff is less duplicate code, but you must avoid loops and keep the setup order clear.
Why should I avoid heavy work in a constructor?
You usually should avoid it because constructors should be fast and predictable. If a constructor does network calls, file access, or retries, object creation becomes slow and harder to test. The tradeoff is between convenience and control. For expensive work, a factory or a separate method is often easier to manage.
20. What are the different types of constructors in C#?Language SpecificEasy
i Question Details
Cover the common constructor forms such as default, parameterized, copy-style, and static construction, and explain when each appears.
Short Interview Answer (30-60 seconds)
In C#, the common constructor types are default, parameterized, copy style, and static. A default constructor runs with no inputs. A parameterized constructor takes values and sets required state. A copy style constructor makes a new object from another object. A static constructor runs once for the type before first use and is used for type level setup.
This question asks about the different ways a C# class can be set up when you make a new object from it. Some versions take no input, some take values, some make a fresh copy from another object, and one runs only once for the type itself. The interviewer wants to know whether you understand how C# starts objects, how data gets placed in them, and which form fits each situation. It also helps you see why each choice matters in practice.
Useful Questions to Ask the Interviewer
Should I include records and structs too?
Do you want a small code example?
How to Explain It in an Interview
Constructors are special methods that prepare an object. A default constructor has no parameters. If you do not write any constructor for a class, C# can create a parameterless one for you. But if you write your own constructor, the compiler does not add that default one. A parameterized constructor takes values and is the best choice when the object needs required data at creation time.
A copy style constructor takes another object and copies its values into the new one. C# does not give every class a built in copy constructor. You write it yourself when you need that behavior. This matters because you must choose between shallow copy and deep copy. If the object holds mutable references, simple copying can make two objects share the same inner data.
A static constructor is different. It belongs to the type, not to one object. It has no parameters and no access modifier, and it runs once before the type is used. It is useful for static fields and one time setup. In production, keep constructors light. Do not do expensive work there unless the object cannot exist without it. If initialization can fail or take time, consider a factory method instead.
Code
using System;
publicsealedclassPerson
{
publicstring Name { get; }
publicint Age { get; }
publicstaticint CreatedCount { get; privateset; }
// Runs once for the type before the first object is used.staticPerson()
{
CreatedCount = 0;
}
// Uses safe starting values when no input is provided.publicPerson() : this("Unknown", 0)
{
}
// Sets the required state when the caller already knows the values.publicPerson(string name, int age)
{
Name = name;
Age = age;
CreatedCount++;
}
// Copies values from another object so the new object starts with the same state.publicPerson(Person other) : this(other.Name, other.Age)
{
}
}
publicstaticclassProgram
{
publicstaticvoidMain()
{
// Calls the default constructor.
Person first = new Person();
// Calls the parameterized constructor.
Person second = new Person("Mina", 28);
// Calls the copy style constructor.
Person third = new Person(second);
Console.WriteLine($"{first.Name}{first.Age}");
Console.WriteLine($"{second.Name}{second.Age}");
Console.WriteLine($"{third.Name}{third.Age}");
Console.WriteLine(Person.CreatedCount);
}
}
Why Interviewers Ask This
The interviewer wants to see whether I know how C# initializes objects, what runs once for a type, and what changes when I write my own constructor. It also shows if I understand safe object setup, copy behavior, and the small rules that affect real code.
Common interview mistakes
A common mistake is thinking C# always adds a parameterless constructor. Another mistake is assuming a copy style constructor is built in for every class. People also forget that a static constructor runs only once and cannot take parameters. A bigger mistake is doing heavy work inside constructors, which can make object creation slow and harder to test.
Interview tip
Start with the four common forms, then say when each one runs. Keep the answer simple and mention one rule that matters in real code, such as the compiler not adding a default constructor after you define your own.
Interviewer may ask next
What happens if a class has only a parameterized constructor?
Direct answer: C# does not add a parameterless constructor in that case. You must pass the required arguments when you create the object. This matters because any code that tries to use new with no values will fail to compile, and it also shows that the type expects required state up front.
When should I use a factory method instead of a constructor?
Direct answer: Use a factory method when object creation needs extra steps, validation, caching, or a clearer creation name. The main tradeoff is that a constructor is simpler for direct setup, but a factory gives you more control when creation is complex or when you want to hide the creation logic from callers.
More questions load as you scroll
Disclaimer: This interview guide is for educational and informational purposes only. It is designed to help readers prepare, but it does not guarantee any interview result, hiring decision, offer, or outcome. Interview questions, hiring criteria, and preferred answers can vary by employer, interviewer, industry, location, and time. The examples and explanations reflect the authors' research and judgment, are provided without warranties of any kind, and should not be treated as the only correct approach. Diagrams are simplified illustrations intended to highlight the main components and their interactions; actual systems and implementations may be more complex. Alternative approaches may be equally valid or better suited to a particular question, context, or interviewer. To the fullest extent permitted by applicable law, the author, contributors, and publisher are not liable for decisions made, actions taken, or losses incurred based on this guide.