1. What is C# Generics?
C# Generics allow us to create a single class or method, interfaces, methods, and delegates that can be used with different types of data. Generics enable you to write more flexible and reusable code by allowing you to create components that can work with any data type.
2. What are C# Partial Classes and Methods?
In Partial classes we can split a class, a struct, a method, or an interface into multiple parts with the same class name into .cs file and with partial keyword . Partial class was first introduced in C# 2.0. We use a specifc keyword to making partial class that is called partial.
Partial classes are very useful for organizing large classes, becasue whenever you will have large classes, the code inside these large class will be mized up and it will have lack of clean oorginization. so keeping clean organization of code we can split a larage class into small parital classes.
3. What is Anonymous Method in C#?
An anonymous method is a method which doesn’t contain any name which is introduced in C# 2.0. In C#, an anonymous method allows you to define a method inline without explicitly declaring a separate named method. It's particularly useful when you need a method as a delegate parameter, such as for event handling or LINQ queries.
// An Anonymous Method
delegate(parameters) {
// method body
};
4. What is Nullable Types in C#?
In C#, nullable types are a feature introduced to allow value types (such as int, double, bool, etc.) to have a value of null, in addition to their normal range of values. This is particularly useful in scenarios where you need to represent the absence of a value or where a value might legitimately be undefined.
Example With Syntax
double? pi = 3.14;
char? letter = 'a';
int m2 = 10;
int? m = m2;
bool? flag = null;
// An array of a nullable value type:
int?[] arr = new int?[10];
5. What is Iterators in C#?
In C#, iterators provide a convenient way to iterate over collections or sequences of data. They allow you to define custom iteration behavior for your classes, similar to how you use foreach with built-in collections like arrays or lists.
Example With Syntax
public IEnumerable<int> MyIteratorMethod()
{
// yield return statements
}
6. What is Covariance and Contravariance in C#?
In C#, covariance and contravariance enable implicit reference conversions for generic type parameters. Covariance (using out) allows a method to return a more derived type than specified by the generic parameter.
Contravariance (using in) allows a method to accept parameters of less derived types. These concepts are commonly used with delegates and interfaces to increase flexibility in type assignments.
In C#, "more derived type" and "less derived type" refer to the relationship between classes in an inheritance hierarchy.
Derived Type:
More derived type : A child class that inherits from another base class.
Less derived type : A base class that is inherited by another child class.
Derived Type: Example
// Less derived (base class)
class Food { }
// More derived (inherits from Food)
class Fruit : Food { }
In above example
More derived type : Fruit is a more derived type than Food. Fruit can be derived from Food class.
Less derived type : Food is a less derived type than Fruit. Food can not be derived from any other base class.
7. What is Anonymous Types in C#?
In C#, anonymous types are a way to create objects without explicitly defining a class. They are defined using the var keyword and an object initializer. Anonymous types are often used in LINQ queries to hold temporary, read-only data. Their properties are inferred by the compiler and cannot be modified after creation.
Example
var person = new { Name = "John", Age = 30 };
// Output: John
Console.WriteLine(person.Name);
8. What is Query Expression in C#?
A query is a set of instructions that describes what data to retrieve from a given data source (or sources) and what shape and organization the returned data should have. A query is distinct from the results that it produces.
Generally, the source data is organized logically as a sequence of elements of the same kind. For example, an SQL database table contains a sequence of rows. In an XML file, there's a "sequence" of XML elements (although XML elements are organized hierarchically in a tree structure). An in-memory collection contains a sequence of objects
9. What is Lambda Expressions in C#?
In C#, lambda expressions are anonymous functions that can contain expressions or statements and are used to create delegates or expression tree types. They provide a concise way to represent inline methods, typically written as (parameters) => expression. For example: (x, y) => x + y
Types of Lambda Expression
There are two types of lambda expression.
Expression Lambdas
Statement Lambdas
1. C# Expression Lambdas:
Lambdas expression contain a single expression and return a value.
Syntax of Expression Lambdas
// Syntax of Expression Lambdas
(parameters) => expression
Example of Expression Lambdas
// Example of Expression Lambdas
(x, y) => x + y
2. C# Statement Lambdas:
These can contain multiple statements enclosed in braces {} and can include control flow.
Syntax of Statement Lambdas
// Syntax of Statement Lambdas
(parameters) => { statements }
Example of Statement Lambdas
// Example of Statement Lambdas
Action<string> greet =name =>
{
string greeting = $"Hello {name}!";
Console.WriteLine(greeting);
};
greet("World");
// Output:
// Hello World!
10. What is Extension Methods in C#?
In C#, extension methods allow you to "add" new methods to existing types without modifying their source code or creating a new derived type. This is particularly useful when working with types you don’t have control over, like .NET framework classes or third-party libraries.
Example With Syntax
public static class ExtensionClass
{
public static return MethodName(this Type type, ...)
{
// Method body
}
}
11. What is Object initializers in C#?
An object initializer in C# is a syntax feature that lets you create and initialize an object in a single statement, without having to explicitly call a constructor followed by separate property assignments.
Example
ClassName obj = new ClassName { Property1 = value1, Property2 = value2 }
12. What is Collection Initializer in C#?
A collection initializer in C# lets you create and populate a collection (like a List, Dictionary, etc.) in a single statement, making the code more concise and readable.
C# Collection Initializer Syntax
var collection = new CollectionType { item1, item2, item3 };
13. What is Dynamic Binding in C#?
Dynamic binding in C# refers to resolving method calls or member access at runtime instead of compile time. This is achieved using the dynamic keyword introduced in C# 4.0.
Example With Sytax
// fruitName is interpreted as string at runtime
dynamic fruitName = "Mango";
14. What is Named Optional Parameters in C#?
C# supports two useful method features: named parameters and optional parameters, which improve code clarity and flexibility when calling methods.
Named parameters gives us a facility to specify arguments by parameter name, not just by position.This improves readability and allows skipping the need to remember parameter order.
Optional parameters allow you to leave out arguments when calling a method.You assign default values in the method definition.
C# Named Parameters : Syntax
// Using named parameters
FruitInfo(name: "Apple", price: 0.86);
15. What is Covariance And Contravariance in Generics in C#?
Covariance and contravariance allow flexibility in assigning generic types when working with inheritance hierarchies — especially with interfaces and delegates.
Covariance allows a method to return a more derived type than originally specified.
Contravariance allows a method to accept arguments of a less derived type.
16. What is C# Await Async in C#?
In C#, async and await are used to perform asynchronous programming, allowing your program to run tasks without blocking the main thread, such as I/O operations, web requests, or file reads.
async modifier: - Marks a method as asynchronous and allows use of await inside.
await keyword: - Tells the compiler to pause execution of the method until the awaited task completes, then resume from that point.
Imagine you're baking a cake. While the cake is in the oven (a time-consuming operation), instead of standing there doing nothing, you go wash dishes or clean the kitchen. You continue once the oven timer beeps. It is real life example for Await Async.
17. What is Caller Info Attributes in C#?
Caller Info Attributes in C# provide metadata about the caller of a method — such as the file name, line number, and member name — at compile time. These are especially useful for logging, debugging, and diagnostics.
18. What is C# Static Import in C#?
Static import in C# (introduced in C# 6.0) allows you to import static members (methods, properties, constants, etc.) from a class so you can use them without qualifying them with the class name.
To simplify code and improve readability, especially when you're using many static members from a utility or helper class (e.g., Math, Console, custom utilities).
You often use Math class functions like Sqrt, Pow, or PI. Instead of writing Math.Sqrt() and Math.PI every time, you can import them statically. It is real life example of C# static import.
C# Static Import Example
using System;
// Static import of Math class
using static System.Math;
// Static import of Console class
using static System.Console;
class CSharpProgram
{
static void Main(string[] args)
{
double radius = 5;
// No need to write Math.PI or Math.Pow
double area = PI * Pow(radius, 2);
// No need to write Console.WriteLine
WriteLine($"Area of circle: {area}");
}
}
Output
Area of circle: 78.53981633974483
19. What is Exception Filters in C#?
Exception filters in C# allow you to conditionally catch exceptions based on a logical expression — without handling the exception unless the condition is true.
Why we use Exception Filters in C# becasue it was Introduced in C# 6.0, exception filters improve control and clarity when dealing with different error conditions.
You're catching falling apples. You only catch the red apples, not the green ones.Similarly, an exception filter lets you catch specific types or conditions of exceptions without swallowing everything. It is real life example of Exception Filters
C# Exception Filters : Syntax
// Exception Filters Syntax
catch (ExceptionType ex) when (condition)
20. What is Auto Property Initializers in C#?
In C#, Auto-Property Initializers let you assign default values to auto-implemented properties directly at the point of declaration, without needing to use a constructor.
Why Use Auto Property Initializers in C# becasue it simplifies class definitions by removing boilerplate code.It was introduced in C# 6.0
Imagine filling out a registration form where some fields already have pre-filled values (e.g., "Country = USA"). You only change them if needed. Similarly, auto-property initializers pre-fill property values. It is real life example of Auto Property Initializers.
C# Auto Property Initializers : Syntax
// Auto Property Initializers Syntax
public DataType PropertyName { get; set; } = defaultValue;
21. What is Expression-Bodied Members in C#?
Expression-bodied members in C# allow you to define methods, properties, constructors, etc., using a single-line expression with the => (lambda-style) syntax instead of full block syntax { ... }.
It was introduced in C# 6.0, and extended in later versions (e.g., C# 7+)
Why use Expression-Bodied Members in C# becasue to simplify code that contains short logic — making it cleaner and more readable.
If someone asks you, “What's 2 + 2?” you don’t write an essay — you just say “4.”Expression-bodied members work the same way for short, obvious operations. It is real life example of Expression-Bodied Members.
C# Expression-Bodied Members : Syntax
// Expression-Bodied Members Syntax
member => expression;
22. What is Null Propagation Operator in C#?
The null propagation operator (?.) in C# lets you safely access members (properties, methods, indexers, etc.) of an object that might be null, without throwing a NullReferenceException.
If the object is null, the whole expression returns null instead of crashing.
23. What is String Interpolation in C#?
String interpolation in C# allows you to insert variables or expressions directly into a string using the $ symbol and curly braces {}. It's a cleaner, more readable alternative to string.Format() or string concatenation.
C# String Interpolation : Syntax
// String Interpolation Syntax
$"Text with {variable} and {expression}"
24. What is Nameof Operator in C#?
The nameof operator in C# returns the name of a variable, type, or member as a string, without hardcoding the name manually. It helps make your code safer and easier to refactor, especially in logging, exceptions, and validation.
C# Nameof Operator : Syntax
//C# Nameof Operator Syntax
nameof(identifier)
25. What is Tuple Deconstruction in C#?
The tuples feature provides concise syntax to group multiple data elements in a lightweight data structure. The following example shows how you can declare a tuple variable, initialize it, and access its data members.
A tuple is a lightweight data structure that groups multiple values into one object. You can use the Tuple class or the newer (T1, T2, ...) syntax introduced in C# 7.0
Deconstruction allows you to unpack the tuple into individual variables in a very readable way.
Imagine a method that calculates the total price and the estimated delivery time for an online order. It needs to return both values. It is real life example of Tuple Deconstruction.
C# Tuple : Syntax
//C# Tuple Syntax
(ValueType1 name1, ValueType2 name2) tupleName = (value1, value2);
26. What is Pattern Matching in C#?
Pattern matching in C# is a feature that allows you to check the shape (type and properties) of data and conditionally extract values from it — in a safe, readable, and expressive way.
C# is Pattern: Syntax
//C# is Pattern Syntax
if (obj is Type varName)
{
/* use varName here */
}
27. What is Local Functions in C#?
Local functions in C# are functions defined inside another method. They're useful when a helper method is only needed within the context of that method, keeping code organized and scoped locally.
You're calculating the total bill at a restaurant. You need a small function to calculate tax — but it’s only used inside the billing method, so you don’t want to make it a separate method in the class. It is real life example of Local Functions.
C# Local Functions Example
using System;
class CSharpProgram
{
static void Main(string[] args)
{
double subtotal = 100.0;
double total = CalculateTotal(subtotal);
Console.WriteLine($"Total bill: ${total}");
}
static double CalculateTotal(double amount)
{
// Local function defined inside the method
double CalculateTax(double value)
{
// 10% tax
return value * 0.1;
}
return amount + CalculateTax(amount);
}
}
28. What is Ref Locals And Ref Returns in C#?
Ref locals allow you to create a reference to a variable or array element, so that when you modify the reference, the original value changes directly.They are useful when you want to work with large data efficiently or change data in-place without copying. A ref return allows a method to return a reference to a variable (instead of a copy). This means the caller can directly modify the original value stored in the calling scope (like an array element, field, or variable).
29. What is Discards Variable in C#?
A discard in C# is represented by the underscore _. It’s used when you don't care about a value — such as when you're ignoring part of a tuple, a return value, or an out parameter. It’s a way to make your code cleaner and clearer, showing that a value is intentionally unused.
You try parsing a string to a number to validate it, but you don’t care about the parsed value — just whether it succeeds. It is real life example of Discards Variable.
C# Discards Method Syntax
// C# Discard return value
_ = SomeMethod();
30. What is Binary Literals And Digit Separators in C#?
Binary literals was introduced in C# 7.0, binary literals use the prefix 0b to represent numbers in binary format.In Digit separators you can use underscores (_) to visually separate digits in numeric literals, making them easier to read.It Works in binary, decimal, and hexadecimal number.
Binary Literals : Syntax
// C# Binary Literals Syntax
0b01010101
For reading complete above tutorial please visit following link : c# advanced interview questions
For more such type of tutrials please visit this site: C-Sharp Tutorial
Thanks for reading.
Top comments (0)