C# Interview Questions
C# Interview Questions
Var :
• var is a statically typed variable.
{
var _varvariable = 999;
_varvariable = “Values of var type changed.”
}
Dynamic :
{
dynamic _dynamicVariable = 100;
_dynamicVariable = “Dynamic Type Variable value
changed”;
}
No Error
Intellisense Help:
_varvariable.length()
_varvariable.Max()
_varvariable.Min()
_varvariable.Last()
Q. Var Vs Let in C#
Var Keyword:
• Function Scope
1. //function scope
2. function get(i){
3. //block scope
4. if(i>2){
5. var a = i;
6. }
7. console.log(i);
}
8. //calling function
9. get(3)
10.
11. //
access variable outside function scope
12. //it will give me an error
13. console.log(i);
o/p:
3
Uncaught ReferenceError: i is not defined at window.onload
• Hoisting
1. //function scope
2. function get(i){
3. //printing i variable
4. //value is undefined
5. console.log(a);
6.
7. //
declare variable after console but this var
iable hoisted to the top at //run time
8. var a = i;
9.
10. //again printing i variable
11. //value is 3
12. console.log(a);
13. }
14. //calling function
15. get(3)
o/p:
undefined
3
1. //function scope
2. function get(i){
3. //a hoisted to the top
4. var a;
5. //
if we don't give any value to variable, by
default, value is undefined.
6. //value is "undefined"
7. console.log(a);
8.
9. //assigning value to a
10. a = i;
11.
12. //value is 3
13. console.log(a);
14. }
15. //calling function
16. get(3)
Let keyword:
• Block Scope
When you try to access let keyword outside block scope, it will
give an error. let variable is available only inside the block
scope.
o/p:
• Hoisting
1. //
program doesn't know about i variable so it
will give me an error.
2. console.log(i);
3. //declare and initilize let variable
4. let i = 25;
o/p:
Take Operator :
The following code gets the top 5 rows from an EMPLOYEE object. It
shows the top 5 rows from the EMPLOYEE table and shows
them in the GridView.
private void GetEmployee()
{
EmployeeOperationDataContext employeeContext
= new EmployeeOperationDataContext();
var employee =
(from emp in employeeContext.EMPLOYEEs
select emp).Take(5);
gridEmployee.DataSource = employee;
gridEmployee.DataBind();
}
The following code gets the top 5 rows from an EMPLOYEE object.
These employees have a salary greater than 1200. They are shown in a
GridView.
private void GetEmployee()
{
EmployeeOperationDataContext employeeContext
= new EmployeeOperationDataContext();
var employee = (from emp in employeeContext.EMPLOYEEs
where emp.SALARY > 1200
select emp).Take(5);
gridEmployee.DataSource = employee;
gridEmployee.DataBind();
}
SKIP Operator:
• The Skip operator bypasses a specified number of contiguous
rows from a sequence/table and returns the remaining table.
• It can skip rows from the top or can be for a certain criteria, in
other words it can also skip rows depending on a certain criteria.
The following code skips top 5 rows from EMPLOYEE object and getting
remaining rows. It shows all rows from EMPLOYEE table except top 5
rows and showing in GridView.
public void GetEmployee()
{
EmployeeOperationDataContext employeeContext
= new EmployeeOperationDataContext();
var employee =
(from emp in employeeContext.EMPLOYEEs
select emp).Skip(5);
gridEmployee.DataSource = employee;
gridEmployee.DataBind();
}
The following code skips 2 rows in the Employee table (these employees
have a salary less than 1300) and returns the remaining rows. It shows
the employee data in a GridView.
private void GetEmployee()
{
EmployeeOperationDataContext employeeContext
= new EmployeeOperationDataContext();
var employee = (from emp in employeeContext.EMPLOYEEs
where emp.SALARY < 1300
select emp).Skip(2);
gridEmployee.DataSource = employee;
gridEmployee.DataBind();
}
using System;
class Calculator
{
// Define methods that match the delegate signature
public static int Add(int a, int b)
{
return a + b;
}
class Program
{
static void Main(string[] args)
{
// Create delegate instances pointing to the methods
MathOperation addDelegate = Calculator.Add;
MathOperation subtractDelegate = Calculator.Subtract;
Q. Events in c#
• Event is a notification mechanism that depends on delegates.
• The events are declared and raised in a class and associated with
the event handlers using delegates within the same class or some
other class.
• The class containing the event is used to publish the event. This is
called the publisher class.
• Some other class that accepts this event is called
the subscriber class. Events use the publisher-subscriber model.
Imagine you're organizing a party. You're the host (event source), and
your friends are the guests (event handlers). You want to notify your
friends when the party is about to start so they can join in the fun.
In this scenario:
Event Source (Host): You, as the host, are the event source. You have
a "PartyStarted" event that you'll trigger when the party begins.
Event Handler (Guests): Your friends are the event handlers. They've
subscribed to the "PartyStarted" event, indicating that they want to be
notified when the party starts.
Event Trigger (Party Start): When the party is ready to start, you trigger
the "PartyStarted" event. This sends a signal to all your friends who
have subscribed to the event.
Event Response (Joining the Party): Your friends receive the event
notification and respond by joining the party. They didn't need to
constantly check with you if the party had started; they simply relied on
the event notification
using System;
class Program
{
static void Main(string[] args)
{
Party myParty = new Party();
Friend friend1 = new Friend("Alice");
Friend friend2 = new Friend("Bob");
In this example, the Party class has a PartyStarted event, and the Friend
class has a JoinParty method. When the party starts, the Party class
triggers the PartyStarted event, and the Friend objects respond by
joining the party. Just like in the real-life analogy, the event allows
communication between different parts of the code without them needing
to know the exact details of each other.
Q. What ic Copy Constructor in C#?
• A copy constructor in object-oriented programming (OOP) is a
constructor that creates a new object by copying the properties
and state of another object.
• It's often used to create a new instance that's a duplicate of an
existing instance, especially when dealing with complex objects or
reference types.
• The copy constructor allows you to clone an object while
preserving its data.
using System;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
// Copy constructor
public Person(Person original)
{
Name = original.Name;
Age = original.Age;
}
}
class Program
{
static void Main(string[] args)
{
Person person1 = new Person { Name = "Alice", Age = 30 };
// Using the copy constructor to create a new person with the same
data
Person person2 = new Person(person1);
Q. SOLID principles in C#
• Single Responsibility Principle (SRP): In C#, this principle
encourages you to create classes that have only one reason to
change. Each class should focus on a single task, making the
code easier to understand and maintain.
• They allow you to define small, inline, unnamed functions that can
be used wherever a delegate type is expected.
• In C#, you can define anonymous functions using the => syntax,
also known as the "goes to" operator. Here's a breakdown of
anonymous functions:
Example:
using System;
class Program
}
• In this example, the anonymous function (a, b) => a + b is
assigned to the add delegate.
• Read-only variables are often used when you want to ensure that
a value remains constant for the lifetime of an object, but you don't
necessarily know its value at compile-time.
class Circle
Constant:
• A constant in C# is a value that is known at compile-time and
cannot be changed throughout the program's execution.
• Constants are declared using the const keyword and are typically
used for values that are not expected to change, like mathematical
constants or configuration values.
Eg.
using System;
class Box
{
public double Width { get; }
public double Height { get; }
public double Depth { get; }
class Program
{
static void Main(string[] args)
{
Box box1 = new Box(10, 20, 30);
Box box2 = new Box(5, 15, 25);
• When you add two boxes using the + operator, it creates a new
box with combined dimensions.
using System;
namespace ExtensionMethodExample
{
char[] chars = input.ToCharArray();
Array.Reverse(chars);
class Program
Console.WriteLine($"Original: {originalString}");
Console.WriteLine($"Reversed: {reversedString}");
Unmanaged Objects:
Q.Explain Filters in C#
• In C#, filters typically refer to attributes or classes that allow you to
apply cross-cutting concerns, such as authentication,
authorization, logging, and exception handling, to your code in a
modular and reusable manner. Filters are commonly used in
ASP.NET MVC and ASP.NET Core to add functionality to actions,
controllers, or globally to the application.
• Caching: Filters can help with output caching, where the output of
an action is cached and served to subsequent requests with the
same parameters, improving performance.
• Authentication Filters
• Authentication filter runs before any other filter or action method.
• Authentication confirms that you are a valid or invalid user.
• Action filters implement the IAuthenticationFilter interface.
• Authorization Filters
• The AuthorizeAttribute and RequireHttpsAttribute are examples of
Authorization Filters.
• Authorization Filters are responsible for checking User Access;
these implement the IAuthorizationFilterinterface in the framework.
• These filters used to implement authentication and authorization
for controller actions.
• For example, the Authorize filter is an example of an Authorization
filter.
• Action Filters
• Action Filter is an attribute that you can apply to a controller action
or an entire controller.
• This filter will be called before and after the action starts executing
and after the action has executed.
• Action filters implement the IActionFilter interface that has two
methods OnActionExecuting and OnActionExecuted.
• OnActionExecuting runs before the Action and gives an
opportunity to cancel the Action call.
• These filters contain logic that is executed before and after a
controller action executes, you can use an action filter, for
instance, to modify the view data that a controller action returns.
• Result Filters
• The OutputCacheAttribute class is an example of Result Filters.
• These implement the IResultFilter interface which like the
IActionFilter has OnResultExecuting and OnResultExecuted.
• These filters contain logic that is executed before and after a view
result is executed.
• Like if you want to modify a view result right before the view is
rendered to the browser.
• ExceptionFilters
• The HandleErrorAttribute class is an example of ExceptionFilters.
• These implement the IExceptionFilter interface and they execute if
there are any unhandled exceptions thrown during the execution
pipeline.
• These filters can be used as an exception filter to handle errors
raised by either your controller actions or controller action results.
Q. Is and As in C#
Is keyword is useful when we want to check if the variables are the same
type or not.
1. class Program
2. {
3. static void Main(string[] args)
4. {
5.
6. object str1 = "Madan";
7. if(str1 is string)
8. {
9.
Console.WriteLine("yes it is a number");
10. Console.ReadLine();
11. }
12.
13. }
14. }
o/p : yes it is a number
1. class Program
2. {
3. static void Main(string[] args)
4. {
5.
6. object str1 = "Madan";
7. string str2 = str1 as string;
8. Console.WriteLine(str2);
9. Console.ReadLine();
10.
11. }
12. }
o/p: Madan
Q. Reflections in C#
• Type Discovery: You can find out details about types, such as
their names, namespaces, base types, and implemented
interfaces.
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
Type type = typeof(Math); // Get the Type object for the Math class
MethodInfo methodInfo = type.GetMethod("Abs"); // Get the Abs
method
Q. What is IN in C#.
The "in" modifier helps improve code clarity and reduces the risk of
unintended side effects in methods that operate on the parameter's
value without altering it. It's often used when you want to emphasize that
a method's purpose is to perform some action based on the parameter's
value without changing it.
class Program
{
static void ProcessReadOnly(in int value)
{
// value = 10; // Error: Cannot assign to parameter 'value' because it
is read-only
Console.WriteLine($"Received value: {value}");
}
In this example, the "in" modifier indicates that the "value" parameter in
the "ProcessReadOnly" method is read-only. Trying to modify the
parameter's value inside the method would result in a compilation error.
Using the "in" modifier can help prevent accidental changes to method
parameters and makes the intent of your code clearer when you want to
emphasize that a parameter is intended to be used without modification.
Q. Interface in c#
• It is like an Abstract Class but it can only contains Abstract
Methods(i.e., Methods with no body)
• Used to Implement Multiple Inheritance.
Eg.1
using System;
public interface A
void m1();
class B:A
console.WriteLine(“M1”);
class c
B b = new B();
b.m1();
console.ReadLine();
Eg.2
using System;
public interface A
void m1();
public interface A1
void m1();
class B:A, A1
console.WriteLine(“M1”);
}
class c
B b = new B();
b.m1();
console.ReadLine();
Q. Binding in C#
In C#, "binding" refers to the process of associating data or values with
user interface elements, such as controls in a graphical user interface
(GUI) or properties of objects in code. Data binding enables
synchronization between the data source and the UI, ensuring that
changes in one are automatically reflected in the other. This simplifies
the development of interactive applications by reducing the need for
manual updates and synchronization.
using System;
using System.Windows.Forms;
namespace DataBindingExample
{
public string UserName { get; set; } = "John";
public MainForm()
InitializeComponent();
BindControls();
}
In this example, the UserName property is bound to the Text property of
the usernameLabel control. When the UserName changes, the label's
text automatically updates. Similarly, clicking the "Change" button
updates the UserName, which in turn updates the label.