0% found this document useful (0 votes)
21 views

C# Interview Question-Answer

Uploaded by

dhaygudesuraj261
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

C# Interview Question-Answer

Uploaded by

dhaygudesuraj261
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

C# interview questions

1. 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
are treated as different.

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

Value Type

 In value type actual value get stored on stack.


 When value type goes out of scope it will remove actual value from stack.
 Value type does not hold null values but it can achieved using nullable type.
 Ex. Integer, Boolean, Struct, etc..

Reference Type

 In reference type references get stored on stack and actual value (object) get stored on
heap.
 When references goes out of scope it will just removes references from stack and actual
value (object) is there in heap.
 Ex. String, Object, Class, etc..

3. What is Boxing and unboxing operation?

Boxing

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

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.

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

• Datatype conversion is nothing but converting one data type to another data type
Example. Converting a int value to a float value or vice versa.

• There are 2 different types of Datatype conversion

1) Implicit Conversion – Compiler automatically does a conversion.


 When there is no loss of data.
 When there is no chance of exception/error

2) Explicit Conversion – When compiler fails for automatic conversion we have to do


conversion explicitly.
 Type cast operator
 Convert class operator
 Parse/TryParse operator
 Is/as keyword

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 or 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 also
there is a chance of Overflow Exception. So compiler will not perform implicit conversion
and we have to use explicit cast here.

5. 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
types like int, bool, float etc.

6. 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 Overflow Exception, Format Exception etc.

7. 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()

8. What is object type ?

• The Object Type is the ultimate base class for all data types in C#

• Object is an alias for System.Object class.

• The object types can be assigned values of any other 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.

9. 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 declaring 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"};

10. 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 type
• 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 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 type of data.

• dynamic test = 10;


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

11. 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;

12. 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 ?
int? i = null;

• Nullable types is the bridge between C# types and Database types. (for example, in SQL
int type can hold null values and in C# by default 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 simplfy 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.

13. Purpose of break, continue, return keywords ?

• The break statement terminates the closest enclosing loop.(i.e. take cursor out of Loop).

• The continue statement skips further statement and passes control to the next iteration.

• The return statement terminates execution of the method in which it appears and
returns control back to calling method.
• If the return statement is inside a try catch block and there is finally block exists, then
finally block will be executed before control returns to the calling method.

14. What is static and instance members of class?

Static

• We use static keyword to declare static members in class.

• Static members are accessed with class name.

• Static methods cannot access any non-static members of the class. They can only access
the static members of that class.

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

Non Static Members or Instance Members

• We can access non-static members by creating the object of the class.

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

• What are different method parameters in C#?

There are 4 different types of method parameters :

Pass by Value

• Any parameter value changes in called method does not reflect in calling method.

Pass by Reference

• Any parameter value changes in called method will reflect in calling method as the
parameter and argument uses the same memory location.

• It is mandatory to initialize value in calling method before passing to method.

• It is not mandatory to assign value in called method before leaving a method.

Output Parameters

• Any parameter value changes in called method will reflect in calling method.

• Internally ref and out keyword works same.

• It is mandatory to assign value in called method before leaving a method.

• It is not mandatory to initialize value in calling method before passing to method.


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

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.

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

16. What is OOPS? What are all pillars of OOPS?

• Object Oriented Programming Language is a programming model where programs are


organized around objects and data rather than action and logic.

• There are 4 different major pillars of OOP :

Inheritance
Polymorphism

Encapsulation

Abstraction

17. What is a class ?

• A class is complex custom type.

• Class contains data members and data functions.

Data Members

 Any field writing inside a class can referred as a data member.


 We can write n number of class field in class.

Member Function

 Any method or function inside a class is nothing but the member function.

18. What is a Object ?

 Object is a runtime entity of class.


 We can create n number of objects of a class.

Student s = new Student();



s is a reference variable of type Student who is pointing to the object type Student.

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

• The purpose of constructor is to initialize class fields.

• Constructor is special member function of a class because it has a same name 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

1) Parameter Less Constructor (Default)


2) Parameterized Constructor
3) Copy 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.

20. 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 automatically called when

I. We access static member.


II. We create object of class.

21. 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 class.

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

• Inheritance provides extensibility it means we can easily plug a new type without
affecting the existing functionalities.

22. 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 class 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 from base class we can use base keyword.

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

• If base and derived class contain same method then a base class reference variable
pointing to a derived class object will call base class method is called method hiding.
• We use new keyword in derived class method because method hiding is intentionally.

• If we don’t provide new keyword then compiler will gives us a warning that if hiding is
intentional then use new keyword.

24. What is polymorphism ? What are types of polymorphism ?

• Polymorphism is nothing but a single thing having multiple forms.

• There are two types of polymorphism

1) Compile time Polymorphism – Method overloading and Operator


Overloading
2) Runtime Polymorphism – Method Overriding

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

• Method overloading is a compile time polymorphism means it checks at compile time.

• Same method name having different forms called method overloading.

• Method can be overloaded on the basis of

1) Number of Parameter
2) Types of Parameter
3) Order of Parameter
4) Kinds of Parameter

 Method can not be overloaded on the basis of

1) Return Type
2) Ref and Out Keyword
3) Using Params

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

27. 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 allow us to overload a method just on basis of ref and out parameter.

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

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

• If base and derived class contain same method then base class reference variable
pointing to a derived class object will call derived class override 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 method at runtime.

30. 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 object.

31. 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 but 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 object 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
locations. 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).

32. What are Properties ? Why should we use properties ? What is auto-implemented
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 requirement.

• 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; }
33. What are indexers?

• Indexers are used to design our indexed based class objects 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, Data Table object, Rows Object uses indexers to access the
values.

34. 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 destroyed 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 affect 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.

35. What is encapsulation and abstraction ? When abstraction and encapsulation comes in
project development ?

• Abstraction is showing relevant information to outside world.


• Encapsulation is a concept of hiding irrelevant data from outside world. It binds data and
functions into a single unit which is called as class.

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

36. 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 implementation 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.

37. 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.
38. What are abstract classes ? Can it be instantiated?

• Abstract classes are created with abstract keyword. They are just like concrete 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.

39. 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 constructor call.

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

41. 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 access 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.

42. 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 virtual 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 will 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.]

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

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

45. 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 anywhere from the containing assembly and from
derived type from outside assembly.

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

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


48. 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, NullReferenceException etc should be mentioned before
Exception class catch block.

49. What is purpose of finally block? Scenario for executing return 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 explicitly 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.]

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

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


NullReferenceException.

51. What is difference between String and StrinBuilder 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.

52. What are enums? What are usage of enums?

• Enums 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.
53. Can we customize values in enum? What is default start value to enum?

• Yes we can customize the values of enums.

• The default start value of enum is 0.

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

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

56. 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
GetHasCode() 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.

57. What it GetType() method?

• Gets the type of the current instance.

int number = 10;


Console.WriteLine(number.GetType());

O/P -> System.Int32

58. 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 runtime.

• GetType() method is invoked with instance whereas typeof method expects the type.

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

60. 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. This method is helps to generate unique hash codes.

61. 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 complex 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.

62. 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 callback methods.


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

63. 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
returned from delegate.

64. 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 separate


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.

65. 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]

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

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

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

69. 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 unboxing
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.

70. 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 performance.

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

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

73. What is reflection? Advantages and disadvantages? Remember some imp classes from
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 dynamically 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.

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

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

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

77. Questions on interface like IEnumerable, IComparer, IComparable, IQueryable interfaces?

IEnumerable
• The IEnumerable<T> is used to iterate a read only collection. It has only one method
GetEnumeartor() which allows you to iterate 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 wherein
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 method 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.

78. What is comparison delegate?

• Collections classes Sort method has 4 different overloads. One of the overload expects
type of 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 achieve sorting of complex types collection.

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

80. 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 throughout the
application and it provides a global point to access that instance.

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

82. 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 class 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 methods 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 of 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 classname.

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.

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


Which will helps us to save some memory.

[Also prepare a syntax to use yield keyword.]

You might also like