C# Interview Questions

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Q. Var Vs Dynamic in C#?

Var :
• var is a statically typed variable.

• It results in a strongly typed variable, in other words the


data type of these variables are inferred at compile time.

• This is done based on the type of value that these


variables are initialized with.

• var type of variables are required to be initialized at the


time of declaration or else they encounter the compile time
error: Implicitly-typed local variables must be initialized.

• var does not allow the type of value assigned to be


changed after it is assigned to. This means that if we
assign an integer value to a var then we cannot assign a
string value to it. This is because, on assigning the integer
value, it will be treated as an integer type thereafter. So
thereafter no other type of value cannot be assigned. For
example, the following code will give a compile time error:

{
var _varvariable = 999;
_varvariable = “Values of var type changed.”
}

Error: Cannot implicitly convert type ‘string’ to ‘int’.

Dynamic :

• Dynamic are dynamically typed variables. This means,


their type is inferred at run-time and not the compile time
in contrast to var type.

• Dynamic type variables need not be initialized when


declared.

• Dynamic allows the type of value to change after it is


assigned to initially.

{
dynamic _dynamicVariable = 100;
_dynamicVariable = “Dynamic Type Variable value
changed”;
}

No Error

Intellisense Help:

• Intellisense help is not available for dynamic type of


variables since their type is unknown until run time. So
intellisense help is not available. Even if you are informed
by the compiler as "This operation will be resolved at run-
time". 

• Intellisense help is available for the var type of variables.


This is because, its type is inferred by the compiler from
the type of value it is assigned and as a result, the
compiler has all the information related to the type. So we
have the intellisense help available. See the code below.
We have a var variable initialized with a string value. So
its type is known to the compiler and we have the
appropriate intellisense help available for it.

_varvariable.length()
_varvariable.Max()
_varvariable.Min()
_varvariable.Last()

Q. Var Vs Let in C#
Var Keyword:

1. var keyword was introduced with JavaScript.


2. It has a function scope.
3. It is hoisted. 

• 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

As you can see in the above example, I have declared a


variable (var a = i) inside block but still I am able to access it
outside the block (output = 3). If I try to access it outside
function scope, it will give me an error (i is not defined).

• Hoisting

When you declare a variable with var keyword, it will be


automatically hoisted to the top of scope. 

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

This happens behind the scene -

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:

1. let keyword was introduced in ES 6 (ES 2015).


2. It has block scope.
3. It is not hoisted.

• 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.

1. //declare a variable with var keyword


2. var i = 4
3. //block scope -start
4. if(i>3)
5. {
6. //
declare a variable with let keyword
7. let j= 5;
8.
9. //
declare a variable with var keyword
10. var k = 8;
11. //it will give me 5
12. console.log("inside block scope
(let)::"+ j);
13. }
14. //block scope -end
15.
16. //it will give me 8.
17. //
var variable are available outside block sc
ope
18.
console.log("ouside block scope (var)::"+ k
);
19.
20. //it will give me an error.
21. //
let variable are not available outside bloc
k scope
22.
console.log("ouside block scope (let)::"+ j
);

o/p:

inside block scope (let)::5


ouside block scope (var)::8
Uncaught ReferenceError: j is not defined at window.onload

• Hoisting

Let keyword is not hoisted.

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:

Uncaught ReferenceError: i is not defined at window.onload

Q. Explain LINQ operator like take and


skip in c#.

Take Operator :

• The Take operator returns a specified number of contiguous rows


from the starting point of the database table.
• The Take operator specifies how many rows we want from the
start position of the table but when we define a criteria in that case
this criteria is evaluated first before the start position is determined.

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();
    }

Q. What is Delegate in c#?


• A delegate in C# is similar to a function pointer in C or C++.

• A delegate is a variable that holds the reference to a method


or pointer to a method.

• A delegate can refer to more than one methods of same return


type and parameters.

• A delegate in C# serves as a blueprint for a method, defining its


input parameters and return type.

• It enables methods to be treated as objects, allowing them to be


assigned to delegate instances.

• Delegates are pivotal for event handling, callbacks, and dynamic


method invocation.

• Understanding delegates showcases an adept command over C#


fundamentals and the ability to craft modular, adaptable, and
maintainable code architectures.

• It's a new type of object in C#


• The entire object we used to define contained data, but a delegate
contains the details of a method.

. Type-Safe Function Pointers: A delegate defines a type that


encapsulates a method signature, including its return type and
parameter types. This makes delegates type-safe, ensuring that
the method you're invoking matches the delegate's signature.

. Declaration: Delegates are declared using the delegate keyword,


followed by the return type and parameter types of the methods it
can reference. For example, delegate int MathOperation(int a, int
b); declares a delegate named MathOperation that can reference
methods taking two int parameters and returning an int.

. Instantiation: Delegate instances are created by assigning a


method that matches the delegate's signature to the delegate
variable. This allows you to create references to methods that can
be invoked later.

. Invocation: You can invoke a delegate like a regular method


using the delegate instance. The delegate then calls the underlying
method.
. Multicast Delegates: Delegates in C# can be multicast, meaning
they can hold references to multiple methods. When a multicast
delegate is invoked, all the referenced methods are called in order.

. Event Handling: Delegates are commonly used to implement


event handling in C#. In event-driven programming, objects can
raise events, and other objects can subscribe to those events by
adding their methods to the delegate.

using System;

// Declare a delegate signature


delegate int MathOperation(int a, int b);

class Calculator
{
// Define methods that match the delegate signature
public static int Add(int a, int b)
{
return a + b;
}

public static int Subtract(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;

// Use the delegates to perform operations


int resultAdd = addDelegate(5, 3); // Calls Calculator.Add(5, 3)
int resultSubtract = subtractDelegate(8, 2); // Calls
Calculator.Subtract(8, 2)

Console.WriteLine("Add result: " + resultAdd);


Console.WriteLine("Subtract result: " + resultSubtract);
}
}

In this example, we define a delegate named MathOperation, which


represents methods that take two integers as parameters and return an
integer. Then, we have a Calculator class with Add and Subtract
methods, both of which match the signature of the MathOperation
delegate. In the Main method, we create delegate instances
(addDelegate and subtractDelegate) that point to the respective
methods. Finally, we use these delegate instances to call the methods
and perform calculations.

Q. Explain Generics in c#.


Generic allows us to make classes and methods - type independent or
type safe

public class Calc


{
public static bool AreEqual<T>(T v1, T v2)
{
return v1.Equals(v2);
}
}

static void Main(String[] args)


{
// bool intEqual = Calc.AreEqual(4,4);

// bool strEqual = Calc.AreEqual (“me”, “you”);

bool equal = Calc.AreEqual<int>(4,4);

bool str = Calc.AreEqual<string>(“me”, “you”);


}

Q. Events in c#
• Event is a notification mechanism that depends on delegates.

• Event is like a wrapper over the delegates to improve its security.

• Events are user actions such as key press, clicks, mouse


movements, etc., or some occurrence such as system generated
notifications.

• Applications need to respond to events when they occur. For


example, interrupts. Events are used for inter-process
communication.

• 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.

• A publisher is an object that contains the definition of the event


and the delegate. The event-delegate association is also defined in
this object. A publisher class object invokes the event and it is
notified to other objects.

• A subscriber is an object that accepts the event and provides an


event handler. The delegate in the publisher class invokes the
method (event handler) of the subscriber class.

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;

public class Party


{
// Define an event named PartyStarted
public event EventHandler PartyStarted;

public void Start()


{
Console.WriteLine("The party is starting!");

// Trigger the PartyStarted event


OnPartyStarted();
}

protected virtual void OnPartyStarted()


{
// Check if there are any subscribers to the event
PartyStarted?.Invoke(this, EventArgs.Empty);
}
}

public class Friend


{
public string Name { get; }

public Friend(string name)


{
Name = name;
}

public void JoinParty(object sender, EventArgs e)


{
Console.WriteLine($"{Name} is joining the party!");
}
}

class Program
{
static void Main(string[] args)
{
Party myParty = new Party();
Friend friend1 = new Friend("Alice");
Friend friend2 = new Friend("Bob");

// Subscribe the JoinParty method of friends to the PartyStarted


event
myParty.PartyStarted += friend1.JoinParty;
myParty.PartyStarted += friend2.JoinParty;

// Start the party (trigger the event)


myParty.Start();
}
}

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);

Console.WriteLine($"Person 1: {person1.Name}, {person1.Age}


years old");
Console.WriteLine($"Person 2: {person2.Name}, {person2.Age}
years old");
}
}
In this example, the Person class has a copy constructor that takes
another Person instance as an argument and creates a new instance
with the same data. The Main method demonstrates creating two
instances of the Person class: person1 and person2. The copy
constructor is used to create person2 based on the data of 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.

• Open/Closed Principle (OCP): In C#, this principle suggests


designing classes and methods in a way that allows extending
functionality without modifying existing code. This can be achieved
through inheritance, interfaces, and abstract classes.

• Liskov Substitution Principle (LSP): In C#, adhere to this


principle when creating derived classes. Derived classes should be
substitutable for their base classes without altering the correctness
of the program. This ensures that polymorphism works correctly.

• Interface Segregation Principle (ISP): In C#, this principle


advises creating specific interfaces for clients rather than having
large, monolithic interfaces. This promotes more focused and
cohesive interfaces.

• Dependency Inversion Principle (DIP): In C#, follow this


principle by designing classes that depend on abstractions rather
than concrete implementations. This allows for more flexibility in
substituting implementations and promotes loose coupling.

Q. What is Anonymous Function in C#?


• Anonymous functions, also known as lambda expressions, are a
feature in many modern programming languages, including C#.

• They allow you to define small, inline, unnamed functions that can
be used wherever a delegate type is expected.

• These functions are especially useful for short and simple


operations that don't warrant a separate method declaration.

• In C#, you can define anonymous functions using the => syntax,
also known as the "goes to" operator. Here's a breakdown of
anonymous functions:

Syntax: (parameters) => expression

Example:

using System;

class Program

delegate int MathOperation(int a, int b);

static void Main(string[] args)

// Using an anonymous function with a delegate

MathOperation add = (a, b) => a + b;

int result = add(5, 3); // Calls the anonymous function

Console.WriteLine("Add result: " + result);

}
• In this example, the anonymous function (a, b) => a + b is
assigned to the add delegate.

• This anonymous function takes two integers as parameters and


returns their sum. It's used just like a regular method with the
delegate, and result will be 8.

• Anonymous functions are often used in scenarios like LINQ


queries, event handlers, and other cases where you need to
provide a short piece of code as an argument without creating a
separate method.

Q. What is Read-Only and Constant


Read-Only:
• A read-only variable in C# is one that can only be assigned a value
once, either at the time of declaration or within the constructor of
the class.

• After the value is assigned, it cannot be modified.

• 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

public readonly double Radius;

public Circle(double radius)

Radius = radius; // Can be assigned within constructor


}

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.

const int DaysInWeek = 7;

Q. Explain Operator Overloading


• The Concepts of Overloading a Function can also be applied to
operators.

• Operator Overloading gives the ability to use the same operator to


do various operations.

• It provides additional capabilities to c# operators when they are


applied to user-defined data types.

• It enables to make user-defined implementations of various


operations where one or both of the operands are of user-defined
class.

• Only the predefined set of c# operators can be overloaded.

• To use operators with user-defined data types, they need to be


overloaded according to programmer’s requirement.

• An operator can be overloaded by defining a function to it.

• The functions of the operator is declared by using the operator


keywords.
• operators may be considered as functions internal to the compiler.
Imagine you have a Box class that represents a physical box. You want
to be able to add two boxes together as if they were stacking on top of
each other.

using System;

class Box
{
public double Width { get; }
public double Height { get; }
public double Depth { get; }

public Box(double width, double height, double depth)


{
Width = width;
Height = height;
Depth = depth;
}
// Operator overloading for +
public static Box operator +(Box box1, Box box2)
{
double totalWidth = box1.Width + box2.Width;
double totalHeight = box1.Height + box2.Height;
double totalDepth = box1.Depth + box2.Depth;
return new Box(totalWidth, totalHeight, totalDepth);
}

public override string ToString()


{
return $"Width: {Width}, Height: {Height}, Depth: {Depth}";
}
}

class Program
{
static void Main(string[] args)
{
Box box1 = new Box(10, 20, 30);
Box box2 = new Box(5, 15, 25);

Box stackedBox = box1 + box2; // Using the overloaded + operator

Console.WriteLine($"Stacked Box: {stackedBox}");


}
}

• In this example, the Box class represents physical boxes.


• The + operator is overloaded to allow adding two Box instances
together, which conceptually means stacking one box on top of
another.

• The operator+ method defines how the addition operation should


work for boxes.

• When you add two boxes using the + operator, it creates a new
box with combined dimensions.

Q. Explain Extension Methods in C#


• Extension methods allow you to inject additional methods without
modifying, deriving or recompiling the original class, struct or
interface.

• Inheritance is a process in which we can inherit the functionalities


of a class.

• There is no inheritance is available for structures.

• Extension methods are defined as static methods but once they


are bind with any class or structure then they convert into non-
static or instance methods.

• If an extension method is defined with the same name and same


signature of an existing method in the class, then extension
method will not be called.

• (this program p) -> It is binding parameter only.

• When you call any extension method no need to provide value to


this binding parameter.

• If you want to provide parameters to extension method then you


can place your parameters after the binding parameters.

• But remember one thing that binding parameters always be the


first parameter in the parameter list.
• Binding parameter is ignored always but not other parameters.

• Only one binding parameter is allowed.

• Extension methods, as name suggests, are additional methods.

• Extension methods are static methods.

• Extension method is a new feature that has been added in c# 3.0

• Extension methods can be added to your own custom class, .NET


framework class, or third party classes or interfaces.

• Existing Class (Original Toolbox): Represents an existing class


in your code.

• New Functionality (New Task): Represents a functionality you


want to add to the existing class.

• Extension Method (Extension Tool): Is a static method that you


create in a separate static class. It appears as if it's a part of the
existing class.

• Applying the Extension Method (Using Extension Tool): You


can now use this extension method on instances of the existing
class without modifying the original class.

using System;

namespace ExtensionMethodExample

public static class StringExtensions

public static string Reverse(this string input)

{
char[] chars = input.ToCharArray();

Array.Reverse(chars);

return new string(chars);

class Program

static void Main(string[] args)

string originalString = "hello";

string reversedString = originalString.Reverse(); // Using the


extension method

Console.WriteLine($"Original: {originalString}");

Console.WriteLine($"Reversed: {reversedString}");

• In this example, the Reverse extension method is added to the


string class.

• This allows you to call the Reverse method directly on string


instances.
• It's like adding a new tool to your toolbox without modifying the
original tools.

Q. Managed and Unmanaged Objects


Managed Objects:

Managed objects in C# are those that are automatically managed by


the .NET Common Language Runtime (CLR). This means that the CLR
takes care of memory allocation, deallocation, and garbage collection for
these objects. Most objects created in C# are managed objects.
Examples include instances of classes, arrays, and strings.

Unmanaged Objects:

Unmanaged objects are those that are not automatically managed by


the CLR. They are typically objects created outside the .NET
environment, often using native code or external libraries. These objects
require manual memory management and resource handling, as the
CLR doesn't automatically track and clean up their memory. Interfacing
with unmanaged objects often involves using techniques like Platform
Invoke (P/Invoke) to work with native code libraries.

Q. Content Negotiation in Web API


• Content negotiation is a process in which a client and a server,
typically in a web-based context, communicate to determine the
most suitable format for exchanging data. The client requests a
resource, and the server responds with the appropriate
representation of that resource based on factors like the client's
preferences, capabilities, and the available formats on the server.

• In the context of web development, content negotiation allows the


client and server to agree on the best format for data exchange,
such as HTML, XML, JSON, or other formats. This ensures that
the client receives data in a format that it can understand and
process effectively.

• Here's a simplified breakdown of the content negotiation process:

• Client Sends a Request: The client (usually a web browser or


application) sends a request to the server for a specific resource.
This request may include information about the formats it can
handle or preferences.
• Server Evaluates the Request: The server receives the request
and examines the information provided by the client, such as
supported content types or languages.

• Server Determines the Response Format: Based on the client's


preferences and the server's capabilities, the server selects the
most suitable format for the response data. This might involve
looking at the Accept headers in the client's request.

• Server Sends Response: The server constructs the response in


the chosen format and sends it back to the client.

• Client Processes the Response: The client receives the


response and processes the data according to the chosen format.

• Content negotiation ensures that different clients, which might


have different capabilities and requirements, can still interact with
the server and receive data in a way that is most effective for
them. It's an important mechanism for enabling flexible and
interoperable communication between different software
components in a networked environment.

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.

• Here's a breakdown of filters in the context of ASP.NET MVC and


ASP.NET Core:

• Authentication and Authorization: Filters can be used to ensure


that users are authenticated (logged in) and authorized (have the
required permissions) to access specific actions or controllers.
This enhances the security of your application by restricting access
to certain parts of it. (IAuthenticationFilter & IAuthorizationFilter)

• Logging and Tracing: Filters allow you to log information about


requests, actions, or exceptions, helping you diagnose issues and
monitor application behavior.

• Exception Handling: Exception filters capture and handle


exceptions that occur during the execution of an action. This
allows you to customize error responses and provide helpful
information to users.

• Validation: Filters can be used to perform validation checks on


inputs before an action is executed, ensuring that the inputs are
valid before processing.

• 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.

• Custom Actions: You can create custom filters to add specific


behavior to actions or controllers. This promotes code reusability
and maintainability.

• In ASP.NET Core, filters are categorized into various types,


including action filters, result filters, exception filters, and resource
filters. Each type focuses on a specific aspect of the request-
response pipeline.

• Overall, filters provide a way to inject common behaviors into


different parts of your application without duplicating code. They
help you keep your code clean, modular, and organized by
separating concerns and promoting the DRY (Don't Repeat
Yourself) principle.

• There are five types of Filters in ASP.NET MVC 5:

• 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

As keyword is helpful when we want to convert an object from one type


to another type. If the  AS keyword failed to convert one type to another
type it will set null value.

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

In the above code, str1 is an object and we are converting an object to a


string.

Key points to remember,


• IS keyword is helpful to check if the object is that type or not 
• AS keyword is helpful too if we want to convert one type to another
type.  
• IS keyword type is boolean and AS keyword is not a boolean type.
• The is operator returns true if the given object is of the same type
whereas as operator returns the object when they are compatible
with the given type.

Q. Reflections in C#

• Reflection in C# is a powerful feature that allows you to inspect,


analyze, and interact with the metadata, types, and members of
objects and assemblies at runtime. It provides the ability to
discover and manipulate information about classes, methods,
fields, properties, and more, even if these details were not known
at compile time.

• Reflection is often used for tasks like:

• Inspecting Metadata: You can retrieve information about


assemblies, types, methods, properties, and fields within an
assembly.

• Creating Instances: You can dynamically create instances of


classes and invoke their methods.

• Accessing Members: You can access and modify fields,


properties, and methods of objects, even private ones.

• Dynamic Loading: You can dynamically load assemblies and


types, allowing you to build plugins or extensions that are loaded
at runtime.

• Attributes: You can read custom attributes applied to classes,


methods, or properties to perform conditional logic or other custom
behavior.

• Serialization: You can generate data in different formats (like


JSON or XML) based on the structure of classes at runtime.

• Reflection in C# is a powerful feature that enables you to inspect


and manipulate the structure, members, and attributes of types
and objects at runtime.

• It allows you to programmatically access information about


assemblies, classes, methods, fields, properties, and more.

• Reflection is commonly used for tasks like generating dynamic


code, interacting with unknown types, and building extensible
applications.

• Reflection provides classes and methods in the System.Reflection


namespace to accomplish tasks such as:

• Type Discovery: You can find out details about types, such as
their names, namespaces, base types, and implemented
interfaces.

• Member Access: You can access fields, properties, methods,


events, and constructors of a type and invoke them dynamically.

• Attribute Inspection: You can read attributes applied to types,


members, or assemblies, enabling you to add custom metadata
and behaviors to your code.

• Dynamic Instantiation: You can create instances of types even if


their names are not known at compile time.

• Dynamic Method Invocation: You can invoke methods on


objects without knowing their types beforehand.

Here's a simple example of using reflection in C# to inspect and call


methods of an object:

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

int result = (int)methodInfo.Invoke(null, new object[] { -5 }); // Invoke


the method
Console.WriteLine($"Absolute value: {result}");
}
}

Q. What is IN in C#.

In C#, the "in" keyword is used as a modifier for method parameters. It


indicates that the parameter is intended to be read-only within the
method, preventing any modifications to the parameter's value. This is
particularly useful for scenarios where you want to ensure that the
method doesn't accidentally or intentionally modify the original value of
the parameter.

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}");
}

static void Main(string[] args)


{
int myValue = 42;
ProcessReadOnly(myValue);
}
}

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.

• Class or Struct Implementing the Interface must override the


methods declared in the interface.

Eg.1

using System;

public interface A

void m1();

class B:A

public void m1()

console.WriteLine(“M1”);

class c

public static void Main(String[] args)

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

public void m1()

console.WriteLine(“M1”);
}

class c

public static void Main(String[] args)

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.

There are several types of binding in C#:

. Data Binding in GUI Applications: In graphical user interface


applications (such as Windows Forms, WPF, or Xamarin), data
binding allows you to connect UI elements like text boxes, labels,
and list boxes to data sources (like databases or collections). This
way, changes in data are automatically reflected in the UI and vice
versa.

. Object Binding: You can bind the properties of objects to UI


controls, allowing changes to the object's properties to be
displayed in the UI, and UI changes to update the object's
properties.

. Model-View-ViewModel (MVVM) Pattern: In WPF applications,


the MVVM pattern relies heavily on data binding to separate the UI
(View) from the underlying data and business logic (ViewModel).

. Binding to Collections: You can bind UI controls to collections


(lists, arrays, etc.), and the controls automatically update when the
collection changes.

. Binding Expressions: Binding expressions can be used to format


and transform data before it's displayed, providing more control
over how data is presented.

Here's a simplified example of data binding in a Windows Forms


application:

using System;

using System.Windows.Forms;

namespace DataBindingExample

public partial class MainForm : Form

{
public string UserName { get; set; } = "John";

public MainForm()

InitializeComponent();

BindControls();

private void BindControls()

usernameLabel.DataBindings.Add("Text", this, "UserName");

private void changeButton_Click(object sender, EventArgs e)

UserName = "Jane"; // UI will update automatically

}
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.

Data binding is a powerful concept that promotes separation of concerns


and simplifies user interface development by reducing the need for
manual synchronization between UI and data.

You might also like