KEMBAR78
C# Interview Questions - Vikul | PDF | Class (Computer Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
34 views24 pages

C# Interview Questions - Vikul

Uploaded by

dhaygudesuraj261
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views24 pages

C# Interview Questions - Vikul

Uploaded by

dhaygudesuraj261
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

C# interview questions

Purpose of Main() method ? Scenario with writing one more main() method ?

Every program needs an entry point to execute. This Main() method is an entry point where program starts its execution. Main( ) method has some
specification

A. It is by default private – Because nobody else can execute it explicitly.

B. It is static – Method can be called without creating instance of its type.

As C# is a case sensitive language it means Main(), main(), MAIN() these method names a re treated as different.

What are value types and reference types in C# give some examples?

Variables that store the actual data are called as Value Types. Value Types are stored on Stack. They contain the actual valu e. Eg. Int, enum, struct
etc.

Variables that store references to actual data are called as Reference Types. Reference type actual data gets stored on heap. Eg. Cl ass, string, object,
array etc.

What is difference between Value type and Reference types?

Value types gets stored on stack and Reference types gets stored on heap and its reference gets stored on Stack.

By default, Value types cannot hold null values but it can be achieved by using nullable types. Reference types can contain n ull values.

Value types gets destroyed or released from the memory when they go out of scope whereas for reference types requires garbage collector to free
memory.

Escape Sequence and verbatim literal ?

Escape Sequence

Escape sequence used to provide literal representations of nonprinting characters and charact ers that usually have special meanings, such as the
double quotation mark (").

For example, if we have to print name in double quotes like ““CSharp”” – this will give you compile time error. It can be achieved by using \
operator.

We have to escape special meaning of double quote “ by preceding it with a back slash \ it with “\”CSharp\””

Most used escape sequence are - \b Backspace, \n New line, \t Horizontal tab, \’ single quote, \” double quote, \\ back slash etc etc.

Verbatim literal

If we are working with folder path we use back slash character eg. “C:\Learn\CSharp”.

This will give a compile time error because back slash \ has some special meaning. We can easily escape that by having path like
“C:\\Learn\\CSharp”.
But problem with this is if the path is too long then it will be quite difficult to maintain the path so we can use of verbatim literal to escape meaning of
back slash \ from folder path.

Path can be re-written like @”C:\Learn\CSharp”

What is Datatype conversion ? What are different way of type conversion ?

Datatype conversion is nothing but converting one data type to another data type for example converting a int value to a flo at value or vice versa.

There are 2 different types of Datatype conversion

Implicit Conversion – Compiler automatically does a conversion.

Explicit Conversion – When compiler fails for automatic conversion we have to do conversion explicitly.

Compiler does the conversion automatically in 2 cases

When there is no loss of information

When there are no chances of runtime exception

If interviewer asks to explain with example then give below example

Converting from a smaller datatype to bigger datatype for example int to float in this case there is no loss of information o r there is no chance of any
exception so compiler will automatically do a conversion which is implicit type conversion. But if we reverse this case let’s say converting a float
value to int then there is definitely a loss of information means int variable will not be able to hold fractional part and a lso there is a chance of
OverflowException. So compiler will not perform implicit conversion and we have to use explicit cast here.

What are different ways of explicit type conversions ?

There are different ways to achieve explicit type conversion –

Type casting.

float a = 10;

int b = (int) a;

Using of Convert class.

float a = 10;

int b = Convert.ToInt32(a);

Using as Keyword.

object a = "some string";

string b = a as string;

We can use Parse and TryParse methods when we need to convert a string to other ty pes like int, bool, float etc.
What is difference between cast operator and Convert class ?

Cast operator handles the exceptions whereas Convert class does not handle and throws the exception. Exception like OverflowE xception,
FormatException etc.

What is difference between Parse and TryParse methods ?

If the number is in a string format you have 2 options - Parse() and TryParse()

Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns a bool indicating whether it succeeded or failed.

We can use Parse() if we are sure the value will be valid, otherwise use TryParse()

What is Boxing and unboxing operation?

Boxing

Converting value type to reference type. This is an implicit conversion.

eg. int i = 10;

object o = i;

Unboxing

Converting reference type to a value type. This needs an explicit cast.

object o = 100;

int j = (int) o;

Boxing and unboxing are performance wise expensive processes. So it is good to avoid boxing and unboxing if not really needed .

What is object type ?

The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object
types can be assigned values of any other types, value types, reference types, predefi ned or user-defined types. However, before assigning values, it
needs type conversion.

When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is
called unboxing.

What is var type ?

Var type are implicitly types variables. They are introduced in C# 3.0. There is no need to mention the data type when declar ing a variable. A local
variable can be declared implicitly using the var keyword in C#.
We have to compulsorily initialize the value when we are declaring a variable with var. Also its value cannot be null at the time of initialization.
var a= 10;
var z = "CSharp";

The main reason behind introducing var type is the introduction of anonymous types in C#

Var type only used as local variable we cannot use it as class level fields or as method parameters.

Interviewer might extend his question further asking what are anonymous types –

Anonymous types allow to create a new types without defining them.

They are extensively used in LINQ expressions whenever you want to return only a few properties from its properties.

eg.

var person = new {Id = 101, Name = "ABC"};

What is difference between var and object type and dynamic keyword?

Var

It is compile time variable and does not require boxing and unboxing. Since Var is a compile time feature, all type checking is done at compile time
only. Once Var has been initialized, you can't change type stored in it.

var test = 10; // after this line test has become of integer ty pe

test = test + 10; // No error

test = "hello"; // Compile time error as test is an integer type

Object

Each object in C# is derived from object type, either directly or indirectly. It is compile time variable and require boxing and unboxing for conversion
and it makes it slow. You can change value type to reference type and vice versa.

object test = 10;

test = test + 10; // Compile time error

test = "hello"; // No error, Boxing happens here

Dynamic

It is run time variable and not require boxing and unboxing. You can assign any value to dynamic and also can change value type stored in same. All
errors on dynamic can be discovered at run time only. We can also say that dynamic is a run time object which can hold any ty pe of data.

dynamic test = 10;

test = test + 10; // No error


test = "hello"; // No error, neither compile time nor run time

Ternary operator in C#?

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.

condition ? first_expression : second_expression;

What is nullable types? And Null coalescing operator ?

In C# types are divided into 2 broad categories.


Value Types - int, float, double, structs, enums etc. Reference Types – Interface, Class, delegates, arrays etc.

By default value types are non nullable. To make them nullable use ?symbol.
int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error)
int? j = 0 (j is nullable int, so j=null is legal)

Nullable types bridge the differences between C# types and Database types. (for example, in SQL int type can hold null values and in C# by defa ult int
is non nullable.)

Interviewer might ask you what is NULL coalescing operator –

If we want to convert from a nullable type to non nullable type then we have to add a check for null value before assignment. So here we can simplify
the assignment by using null coalescing operator ??.

int? i = null; // here i is nullable type

int j = i ?? 0; // as j is non nullable type it can not hold null value. So, here if i value is null then 0 will be assign to j or else i value.

Purpose of break, continue, return keywords ?

The break statement terminates the closest enclosing loop or switch statement in which it appears.

The continue statement passes control to the next iteration of the enclosing while, do, for, or foreach statement in which it appears.

return

The return statement terminates execution of the method in which it appears and returns control to the calling method. If the method is a void type,
the return statement can be omitted. But we can write return in a method which has void return type if your intention to pass control back to calling
method.

If the return statement is inside a try block and there is finally block exists, then finally will be executed before control returns to the calling method.
What is static and instance members of class?

Static

We use static keyword to declare static members in class.

There will be only a single copy of static members regardless of how many instances of the class are created.

Static members are accessed with class name.

Static methods cannot access any instance members of the class. They can only access the static members of that class.

Instance Members or Non Static Members

There will be different copies of these members with every objects.

We have to access these members by creating the object of the class.

What are different method parameters in C#?

There are 4 different types of method parameters :

Pass by Value:- Parameter value changed in called method will not going to be reflect in calling method.

Pass by Reference:- Changes happened in called method will reflect in calling method as the parameter and argument uses the same memory location.
It is mandatory to initialize the value before passing to method.

Output Parameters:- By default method can return only a single value. If we want to return more than one value from a method then we can use output
parameters. It is mandatory to assign values to output parameters before leaving a method.

Parameter Arrays:- If a method has array as input parameter then we can use params keyword with that parameter. Advantages of using parameter
arrays are we can pass comma separated values instead of creating and passing array as argument. Also we can call that method without passing any
parameter i.e. We can achieve optional method parameter using parameter arrays.

What is difference between ref and out parameters ? When to use one over another ?

Output parameters are used when we want to return more than one value from a method. It is mandatory to initialize value before passing a parameter
as ref parameter whereas for output parameter is not mandate. So, if there is need of using that assigned value before callin g method then we can think
of using ref parameter instead out parameter. It is mandatory to assign values to out parameters before control leaves the method whereas it is not
mandate for ref parameter. So when it is required that a method should assign and return values then we can use of out parame ter instead ref
parameter.

What are all ways available in C# to make method parameters as optional?

There are 4 different ways we can make a parameter as optional parameter :

Method overloading :- We can overload methods on basis of number of parameters to make optional parameter.

Parameter Arrays :- We can use parameter arrays to make optional parameter as it allows us to call method without passing value for params
parameter.
Default Value :- We can specify default values to parameters to make them optional. If we are specifying default values then it should be from right to
left.

Optional Attribute :- We can use OptionalAttribute with parameter to make it optional.

What is OOPS? What are all pillars of OOPS?

Object Oriented Programming is a programming model where programs are organized around objects and data rather than action an d logic.

There are 4 different major pillars of OOP :

Encapsulation, Abstraction, Inheritance and Polymorphism.

What is a class and object ?

A class is complex custom type. Class contains data members and member functions.

A object is a instance of class and also can be considered as a runtime entity of a class.

We can create multiple objects of a class.

What is purpose of constructor ? How it differs from normal member function?

Constructor is special member function of a class because it has a same na me as that of class. Constructors are automatically called when we create
object of a class. It does not have return type as that of method because main purpose of constructors is to initialize class fields.

There are different types of constructors we can write inside a class like Default Parameter less Constructor, Parameterized Constructor, Copy
Constructor, Static Constructor even a constructor can be private or protected constructor.

Compiler automatically provides a default parameter less constructor but if there is parameterized constructor then we have to explicitly write default
parameter less constructor.

What is purpose of static constructor ? When it will get called?

Static constructors are used to initialize static fields of a class. Static constructors are called only once regardless of number of instances of a class.
Static constructors are called before instance constructor gets called on object creation. Static constructors are automatica lly called when we access
static field from class.

What is inheritance what are uses of inheritance?

Inheritance is the ability to create a class from another class, a parent or base class properties are derived into a child or derived cl ass. Inheritance
provides us code reusability means we can use the existing properties and functionalities from the base class into derived classes. Inheritance provides
a specialization it means a derived class is a specialized class which has all properties of base class as well as its own sp ecific properties. Inheritance
provides extensibility it means we can easily plug a new type without affecting the existing functionalities.

What is use of this and base keywords?


this keyword refers to current instance of a class. If we want to access any instance member of c lass we can access them by using this keyword.

base keyword is used to refer the instance of base class. If we want to access or call constructor or any other instance member fr om base class we can
use base keyword.

What is method hiding ? Scenario of object creation and calling methods.

We use new keyword to hide the existing base implementation of a method in derived class. The method signature will be same in base cla ss and in
derived class. If we don’t provide new keyword then compiler will gives us a warning that if hiding is intentional then use new keyword. In method
hiding a base class reference variable pointing to a derived class object will invoke base implementation.

internal class A

public virtual void Print()

Console.WriteLine("Class A Print Method");

internal class B : A

public new void Print() // What if we are not specify new keyword ?

Console.WriteLine("Class B Print Method");

internal class C : B

/* Can we override the print method which is marked new in base class ?

:- No. The method should be either abstract or virtual or override in base class in order to override it in derived class

*/

public new void Print()

{
Console.WriteLine("Class C Print Method");

B b = new A(); // This is not possible

b.Print();

A a = new B();

a.Print(); // Which method will get called ? class A Print method called.

What is polymorphism ? What are types of polymorphism ?

Polymorphism is nothing but a single thing having multiple forms.

There are two types of polymorphism

Compile time Polymorphism – Method overloading and Operator Overloading

Runtime Polymorphism – Method Overriding

What is method overloading? On what basis a method can be overloaded?

A same method name can have different forms on basis of number of parameters, order of parameters, types of parameters and kinds of parameters.

Here types means any data types like int, float, double etc and kinds meaning out, ref, params.

Can method overloaded on basis of just return type ? if no, then why?

No. Method cannot be overloaded just on basis of return type. Return type is not considered in method signature while method overloading.

This behaviour is by design and it is because to avoid confusion of a developer that what will be the output of the method if the method is same and just
changed with the return type.

//GetNumber method is not overloaded

public int GetNumber()

return 10;

public float GetNumber()

{
return 10;

Can method overloaded with out and ref?

Method cannot be overloaded just on basis of ref and out keyword.

At compile time both ref and out refers as same and internally both works same. So compiler does not allow us to overload a m ethod just on basis of
ref and out parameter.

//Cannot define overloaded method 'Print' because it differs from anothe r method only on ref and out

public void Print(out int number)

public void Print(ref int number)

Can method overloaded with params (parameter arrays), why?

We cannot overload a method just on basis of params keyword. Compiler does not find any difference in normal array parameter and a parameter
array at compile time.

//already defines a member called 'Print' with the same parameter types

public void Print(int[] number)

public void Print(params int[] number)

What is method overriding? Why it is called runtime polymorphism?

A base class reference variable pointing to a derived class object will invoke a derived class overridden method.

In order to override a method in derived class that method should be virtual or abstract or override in base class.

Method overriding is called as runtime polymorphism because CLR checks the type of object and call particular version of meth od at runtime.
What is difference between method hiding and method overriding? Scenarios of calling metho ds with multiple object creation scenarios?

We hide a method using new keyword whereas we use override keyword to override a method.

For method overriding it is mandatory that the method should be override virtual or abstract in base class whereas for meth od hiding it is not
mandatory.

In method hiding, a base class reference variable pointing to a derived class object will invoke a base class implementation whereas in method
overriding a base class object pointing to a derived class object will invoke a de rived class overridden implementation.

What is difference between Method overloading and method overriding?

Method overloading and method overriding both are the types of polymorphism.

Method overloading is a compile time polymorphism because at compile time only it is known that which overloaded method will get invoke on
execution.

Method overriding is a runtime polymorphism because which method will get called is decided at runtime based on the type of o bject.

What is Association, Aggregation and Composition in C#?

Association

Association is a relationship between the objects. Just like Inheritance defines the ‘is a’ relationship, Association defines ‘has a’ or using
relationships. In short, Association means an object “uses” another object.

We can define one-to-one, one-to-many, many-to-one and many-to-many objects relationships.

Aggregation

Aggregation is a special type of association. It is a direct association among the objects.

For example, departments and employees, a department has many employees b ut a single employee is not associated with multiple departments. In this
case both the objects have their own life cycle. Employees may exist without a department. Here, department can be called an owner object and the
employee can be called a child object.

Composition

Composition is special type of Aggregation. It is a strong type of Aggregation. In this type of Aggregation the child object does not have their own life
cycle. The child object's life depends on the parent's life cycle. Only the parent obj ect has an independent life cycle. If we delete the parent object then
the child object(s) will also be deleted. We can define the Composition as a "Part of" relationship.

For example, the company and company location, a single company has multiple locatio ns. If we delete the company then all the company locations
are automatically deleted. The company location does not have their independent life cycle, it depends on the company object' s life (parent object).

What are Properties ? Why should we use properties ? What is autoimplemented properties?

Properties are used just like they are public fields of a class. Properties are used to encapsulate and protect the private fields. We can write custom
logic to validate the user data before it is actually assigned to or retrieved from private fields.

Using get and set access modifiers, we can create Read Only, Write Only and Read Write Properties depending on our requiremen t.
Auto implemented properties were introduced in C#3.0, with this feature we do not need to declare a separate private field for a property. Framework
automatically creates a private field for the declared property. Eg. Public string Name{ get; set; }

What are indexers?

Indexers are used to design our class objects indexed based just like an array.

We create Indexers by using “this” keyword. We can overload the indexers just like we overload a method.

In real time, Session object, DataTable object, Rows Object uses indexers to access the values.

What is difference between class and struct?

A struct is a value type and they get stored on the stack whereas class is reference type and they get stored on the heap.

Struct gets immediately destroyed from the memory once they go out of scope whereas for class only reference variable gets de stroyed after it goes out
of scope and the actual object get released by garbage collector.

When we copy one struct to another struct a new struct gets created and any modification on one struct will not going to affe ct the other struct whereas
when we copy one class to another class we get a new copy of reference variable which actually points to same object on heap. So any change in one
class object will going to affect on other class object.

Struct cannot have destructors whereas a class can have destructors.

Struct cannot have explicit parameter less constructor whereas a class can have.

A class or struct cannot inherit from another struct because struct are sealed type.

What is encapsulation and abstraction ? When abstraction and encapsulation comes in proj ect development ?

Encapsulation is a concept of hiding unnecessary data from outside world. It binds data and functions into a single unit whic h is called as class.

Abstraction is showing relevant information to outside world.

Abstraction comes at design level whereas Encapsulation comes at implementation level.

If we talk in terms of coding perspective, public fields shows abstraction and private fields shows encapsulation.

What are interfaces ? What are advantages using interfaces ?

Interfaces are just like classes but they just have declarations and not definitions.

Interfaces cannot be instantiated but an interface reference variable can point to a class which implements that interface.

If a class implementing an interface it is mandatory to provide imp lementation to all of the interface members.

Interfaces cannot have fields.

Interfaces members are by default public even we cannot specify public access specifier explicitly to any of its member.

Multiple class inheritance is not possible in C# but we can achieve it with interfaces.
Interfaces are used to implement SOLID principles and Design patterns.

What is explicit interface implementation ? When there will be need of implementing interface explicitly.

When we are implementing 2 or more interfaces in a class and those interfaces are having same method signature. Then we have to implement those
interfaces explicitly in order to give implementation to all of the interfaces.

We have to prefix method name with interface name while implementing interface explicitly.

This implemented methods are public by default. We cannot specify any other access modifier even a public.

To call particular method we have 2 approaches –

Creating interface reference variable pointing to class object

Creating a class object and then type casting as interface and invoking a method.

What are abstract classes ? Can it be instantiated?

Abstract classes are created with abstract keyword. They are just like normal classes but they can have both abstract and non -abstract members.
Abstract members meaning members with just declarations.

Abstract classes are used as base types.

Abstract classes cannot be instantiated but an abstract class reference variable can point to a derived class object.

Can abstract class have a constructor? When it will get called?

Yes. Abstract class can contain constructors.

Though we cannot create instance of abstract class but its reference variable can point to a derived class object.

Abstract class constructors get called before derived class constructo r call.

What is sealed class/struct?

Sealed class or struct are prevented from inheritance. It means Sealed classes cannot be used as base class.

Sealed class cannot be abstract at the same time.

What is difference between interface and abstract class? When to use interface over abstract class or vice versa.

Interface cannot have definition for any of its member whereas abstract class can have non -abstract members.

Interfaces cannot have fields whereas abstract class can contain field.
Interface members access modifiers are public by default and we cannot specify any other even a public whereas abstract class members a ccess
specifers can be changed.

As Interfaces does have just declarations and also it does not contain fields so if there is situation that all the derived classes has different
implementation but you have to provide same method signature then we can go with interfaces.

An abstract class can have fields and definitions for its members so if there is a situation that few of the derived classes sharing same implementation
then we can think of using abstract class instead of interface.

Why multiple class inheritance is not possible In C# ? How to overcome it.

Multiple class inheritance is not possible in C# it is also called as Diamond Problem.

Let’s say we have one class A which is derived by two classes B and C. Class B and C has overridden method which was marked v irtual in class A.

Now if we derive class B and C in a new class D and we are not providing any implementation in class D.

So, if we create an object of class D then which method implementation should get call here from class B or class C. There wi ll be an ambiguity in
calling 2 different copies of overridden method. This problem is called as Diamond Problem.

We can achieve multiple class inheritance using interfaces. [Interviewer can ask to write a code snippet here.]

What are all access specifiers in C# ?

There are 5 different access modifiers available in C#.

Private – Its accessibility is only within a containing type.

Protected – It is accessible within containing type as well as in derived type in same assembly or from different assembly.

Public – It is accessible from anywhere in the program.

Internal – It is accessible from anywhere in the same assembly.

Protected Internal – It is accessible anywhere within same assembly and from derived type in different assembly.

We can have only public and internal access modifiers with types whereas we can use all the 5 access modifiers with type members.

What is default access specifier for type and type members?

Default access modifier for a type is internal.

Default access modifier for types member is private.

What is internal and protected internal access specifiers?

Internal access modifiers are accessible from anywhere within the same assembly. We cannot access them outside assembly.
Protected internal is can be considered as combination of protected and internal access specifiers means it is accessible any where from the containing
assembly and from derived type from outside assembly.

Why there is need of exception handling?

Exceptions are nothing but runtime unforeseen errors of an application.

It is always a bad practice in showing yellow screen to end user which contains some application specific information.

This information is meaningless for a normal user whereas useful for a hacker to hack your application.

So it is always recommended to do a proper exception handling.

Can a try block have multiple catch block ? Scenario of using Exception classes while using multiple catch blocks ?

Yes. One try block can have multiple catch blocks.

But as all exception classes are derived from Exception base class we have to specify Exception class in the end catch block. If we specify it at the top
then we will get compiler error.

So if we want more than one catch block then all specific exception classes like FileNotFoundException, NullReferenceExceptio n etc should be
mentioned before Exception class catch block.

What is purpose of finally block? Scenario for executing retu rn statements.

Finally block is guaranteed to be executed in both the cases if there is error occurs or not. Also it gets executed if there is any error occurs in catch
block.

So we can use finally block to close the open connection or if we want to explic itly free the resources.

[Scenarios can be asked based on return statement or using Response.Redirect, Server.Transfer, Server.Execute by writing them in try catch and
finally blocks.]

What is difference between Convert.ToString() and ToString() methods?

Convert.ToString() handles NULL whereas ToString() doesn’t and it throws NullReferenceException.

What is difference between String and StringBuilder class?

StringBuilder is mutable whereas String is immutable.

StringBuilder objects are mutable so they offer better performance than string objects when heavy string manipulation is involved.
What are enums? What are usage of enums?

enum are strongly typed constants.

If a program uses set of integral numbers we can replace them with enums. This will increase the code readability and maintainability.

Can we customize values in enum? What is default start value to enum?

Yes we can customize the values of enum.

The default start value of enum is 0.

What is default underlying type to enum? Can we change its underlying type to some other type?

Default underlying type of enum is int.

We can anytime change underlying type to any other integral datatypes like short, int16 etc depending on the size we want to store.

What is difference between enum and Enum class?

enum is a keyword use to create enumerations whereas Enum class contains static methods like GetValues(), GetNames() which can be used to list
enum underlying type values and their names.

What are all default methods comes with every type in dot net? From where they are derived? Can we override them?

All types in dot net directly or indirectly derived from System.Object class.

So with all types by default we get 4 methods GetType(), ToString(), Equals() and GetHashCode() which are actually inherited from System.Object
class.

All these 4 methods are virtual in Object class so we can anytime override them in different types.

What it GetType() method?

Gets the type of the current instance.

int number = 10;

Console.WriteLine(number.GetType());

O/P -> System.Int32

What is difference between typeof and GetType() method?

Both the methods are used to get the type of the current instance.

For typeof method type is known as compile time whereas GetType() method is used to get exact type of current instance at run time.

GetType() method is invoked with instance whereas typeof method expects the type.
Why there is need of overriding ToString() method?

When we invoke ToString() method on any simple types it gives us the string representation of that current type.

But if we invoke ToString() method on Complex types like Customer, Employee it gives us the fully qualified name of the type that means namespace
name followed by type name.

So to give a meaningful string representation for complex types we can override ToString() method.

Why to override Equals() method? Is there is any warning/error associates with just overriding Equals method? If yes, how to fix it?

Equals() method works fine when there are value types but when it comes to reference types it checks only reference equality and not value equality.

So we can override this Equals() method to check value equality for reference types.

There is one warning when we override Equals() method and that is we have to override GetHashCode() method also. Thi s method is helps to generate
unique hash codes.

Can we override == operator?

All arithmetic operators works fine when there are simple types as operands like int, string etc. But when it comes to comple x types like Customer
class, Employee class it gives compile time error saying operator cannot apply on type like Customer.

If we use == operators with complex types it just check reference equality and not value equality. In order to achieve value equality we have to
override == methods.

What are delegates? Why delegates are type safe?

Delegates are type safe function pointers.

Delegates allow methods to be passed as parameters.

Delegates are used to define call back methods.

Delegates signature should get match with method signature that’s why it is calle d as type safe.

What are multicast delegates?

A delegate pointing to multiple methods called as multicast delegate.

It will help to call multiple methods on a single event.

If the methods has return type or out parameter then the last method value get ret urned from delegate.

What are anonymous methods and extension methods?


Anonymous methods :

Anonymous methods are nothing but methods without name. They were introduced in C#2.0.

Anonymous methods allows us to create delegate instance without having a sep arate method.

Anonymous methods are created using delegate keyword.

Extension Methods :

Extension methods are used to extend the functionality of any existing type.

These methods are public static methods and its first parameter is prefixed with this keyword. It is mandatory to write extension method in public static
class.

What is lambda expression? Interviewer can ask to write a small program using lambda expressions.

Lambda expression are simplified way to write LINQ queries. They were introduced in C#3.0.

Lambda Expressions are more convenient than anonymous methods.

[Interviewer can ask to write lambda expressions based on some customer list to find particular customer data we have to use LINQ extension methods
and lambda expression to achieve this]

What is difference between anonymous method and lambda expression?

Lambda expressions are just new way to write anonymous methods.

There is only single difference between them is for anonymous methods if parameters are not used then we can omit them but for lambda expression we
cannot omit the parameters list.

What are types of delegates? Action, Func and Predicate Delegate?

Basically there are 2 types of delegates

Singlecast delegate – Delegate pointing to a single method.

Multicast delegate – Delegate Pointing to multiple methods.

Apart from these types we have few generic delegates which extensively used in LINQ methods.

Action Delegate – Delegate has type T as input parameter and void as return type.

Predicate Delegate – Delegate has type T as input parameter and bool as return type.

Func Delegate – This delegate has around 17 overloads. Which takes T as input parameters and T as output parameter.

We choose this delegates depending on our requirement.


What is generics? Name some generic collections and non generic collections?

Generics allows us to design classes and methods decoupled from the data types.

Which avoid boxing and unboxing operations and offers better performance.

List<T>, Dictionary<T>, Stack<T>, Queue<T> are few examples of generic collections classes.

ArrayList, HashTable, SortedList, Stack, Queue are few examples of non generic collections classes.

What is difference between ArrayList and List<> ?

ArrayList is a non-generic collection class and resides in System.Collection namespace whereas List is a generic class and resides in
System.Collections.Generic namespace.

ArrayList is object based it is not type safe and there is associated boxing and unb oxing operations which is overhead to performance.

Whereas List is type safe and there is no boxing and unboxing operations which actually helps to improve system performance.

What is difference between HashTable and Dictionary<>?

Both HashTable and Dictionary are Key Value Pair collections.

HashTable is a non-generic collection class and resides in System.Collection namespace whereas Dictionary is a generic class and resides in
System.Collections.Generic namespace.

HashTable is object based it is not type safe and there is associated boxing and unboxing operations which is overhead to performance.

Whereas Dictionary is type safe and there is no boxing and unboxing operations which actually helps to improve system perform ance.

What is advantage of generics collections over non generic collections?

Generic collections are type safe.

Being type safety there will not be any overhead of operations like boxing unboxing so it helps to improve the performance.

What is Tuple?

A tuple is an ordered sequence, immutable, fixed size and of heterogeneous objects.

Tuple were introduced in C#4.0.

Tuple can be used as return type of a method whereas we cannot use anonymous types as return type.

What is reflection? Advantages and disadvantages? Remember some imp classes fr om System.Reflection namespace.

Reflection is the ability of inspecting an assemblies metadata at runtime. It is used to find all types in an assembly and dy namically invoke methods of
an assembly.
We can use reflection to dynamically create an instance of a type about which we don’t have any information at compile time. So, reflection enables we
to use code that is not available at compile time.

Reflections are extensively used by IDE or UI designer, for ASP.NET Server controls the properties window uses reflection to show all properties of
control.

All classes are present in System.Reflection namespace. We use Activator class from this namespace to create instance of a type.

What is early binding and late binding?

Early binding gives errors at compile time with late binding there is a risk of runtime exceptions.

Early binding is much better for performance and should always be prepared over late binding. Late binding is used only when we are not aware about
the objects at compile time.

What is eager loading and lazy loading in C#?

In eager loading all the objects are initialized in memory as soon as the objects are created.

In Lazy loading we delay the loading of the objects until the point where we need it. So, Lazy loading is nothing but on demand object loading rather
than loading object unnecessary.

We have System.Lazy class to implement lazy loading.

What are partial classes and rules to create partial classes?

Partial classes allow us to split a class into 2 or more files. All these parts then combined into a single class, when the application is compiled.

Visual studio uses partial classes to separate automatically generated system code .aspx.designer.cs file from the developer’s code .aspx.cs file.

[If interviewer asks for rules then explain below set of rules]

All parts should have partial keyword.

All parts should have same access modifiers.

If one part is marked abstract then entire type is considered abstract.

If one part is marked sealed then entire type is considered sealed.

Multiple class inheritance is not possible in C# so different parts should not inherit different base classes.

What are partial methods? Anything can be asked related to rules followed during creating partial methods?

Partial class or struct can contain partial methods.

Partial method created using partial keyword and it has two parts – the Definition and the implementation.

Partial methods are private by default. We cannot specify any other modifier even private.
Partial method implementation is optional. If we not provide implementation then complier removes its declaration as well as all the calls.

Partial method return type must be void. Giving any other type gives compile time error.

Questions on interface like IEnumerable, IComparer, IComparable, IQuerya ble interfaces?

IEnumerable

The IEnumerable<T> is used to iterate a read only collection. It has only one method GetEnumeartor() which allows you to iter ate the read only
collection using a foreach loop. It only iterates in the forward direction.

It does not contain any other functions like add, remove, count etc. So you cannot add, remove objects in IEnumerable collection.

It provides enumerator to iterate collection in forward direction.

IQueryable

IQueryable<T> allows you to execute a query against a specific data source where in type of data is not specified.

It extends the IEnumerable, hence it allows you to iterate over collection using the foreach statement. All the properties of IQueryable are read only.
IQueryable<T> extends IQueryable and the IEnumerable.

IComparable

Defines a generalized type-specific comparison method that a value type or class implements to order or sort its instances.

By default, all simple types implements IComparable interface so it is possible to invoke Sort me thod on simple type collections.

Whereas for Complex types collection we have to implement IComparable’s CompareTo method in order to Sort the collection.

IComparer

It exposes a Compare method that compares two objects.

Sort method has overloads where its expects a IComparer type. So we can implement IComparer interface to the class and we can sort it on basis of
any of its property.

What is comparison delegate?

Collections classes Sort method has 4 different overloads. One of the overload expects type o f Comparison delegate object.

We can write a method as delegate signature and we can pass this method to delegate instance. This is one of the way to achie ve sorting of complex
types collection.
How to restrict a class for instantiation?

We can restrict a class for its instantiation by making that class as a static class or we can write a private constructor in that class.

Private constructor , how to initialize? where it is used? what is singleton?

When we write a private or protected constructor in a class we cannot create instance of that class from outside of that class.

We create the instance of a class in that class itself. We use public static method to expose the instance.

Singleton pattern ensures that there will be single copy of object throughou t the application and it provides a global point to access that instance.

What is difference between Static class and a Singleton class?

A Static class does not have non static or instance members whereas in Singleton class we can have both static and instance members.

Singleton class can implements interface whereas static class cannot implement interface.

We cannot pass static class to a method whereas we can pass single instance of singleton class to a method.

We can dispose the object of singleton class but not of static class.

How to create a instance of singleton class?

Singleton class exposes a single instance through a public static method.

class Singleton

private static Singleton _instance;

private Singleton()

public static Singleton Instance()

if (_instance == null)

_instance = new Singleton();

}
return _instance;

We can write below code to create instance of singleton class.

Singleton s1 = Singleton.Instance();

Singleton s2 = Singleton.Instance();

[Please note that here s1 == s2 will be true as both are referring to same object.]

Inheritance scenarios - like multilevel inheritance with new and override keywords.

Scenario based questions can be asked here –

Let’s say there are 3 classes A, B and C. Class B is inheriting cla ss A and class C is inheriting class B.

There will be a method which will be virtual in class A and it will be hidden by class B and C with new keyword. Then which m ethods will get called
with below set of objects.

A a1 = new B();

A a2 = new C();

B b1 = new C();

Same example can be replaced with override keyword or combination of new and override methods. We have to think on the type o f object and give the
answers.

What are static, constant and read only?

Static fields have a single copy irrespective of number of instances of a class. They are accessed with class name.

Constant

Constant variables value cannot be changed throughout the program.

They are by default static.

It is mandatory to initialize the value at the time of declaration.

– ReadOnly

ReadOnly fields are also similar to constant variables but we can change its value at runtime through non static constructors.

It is also not mandatory to assign value at the time of declaration.


We can also have static ReadOnly fields in which we can assign value at runtime through static constructor but only once.

What is use of yield keyword?

Yield keyword helps us to do custom Stateful iteration over .Net collections.

We can customize iteration through a collection without creating a temporary collection. Whic h will helps us to save some memory.

[Also prepare a syntax to use yield keyword.]

You might also like