C# Interview Question-Answer
C# Interview Question-Answer
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
• 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
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..
Boxing
int i = 10;
object o = i;
Unboxing
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.
• 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.
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.
• Type casting.
float a = 10;
int b = (int) a;
• Using of Convert class.
float a = 10;
int b = Convert.ToInt32(a);
• Using as Keyword.
We can use Parse and TryParse methods when we need to convert a string to other
types like int, bool, float etc.
• Cast operator handles the exceptions whereas Convert class does not handle and throws
the exception.
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()
• The Object Type is the ultimate base class for all data types in C#
• 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.
• 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 –
• They are extensively used in LINQ expressions whenever you want to return only a few
properties from its properties.
eg.
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.
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.
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.
• The conditional operator (?:) returns one of two values depending on the value of a
Boolean expression.
• 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.)
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 ??.
• 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.
Static
• 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.
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.
Output Parameters
• Any parameter value changes in called method will reflect in calling 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.
15. What are all ways available in C# to make method parameters as optional?
Method overloading
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
Optional Attribute
Inheritance
Polymorphism
Encapsulation
Abstraction
Data Members
Member Function
Any method or function inside a class is nothing but the member function.
19. 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 name as that of
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
• Static constructors are called only once regardless of number of instances of a class.
• 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 extensibility it means we can easily plug a new type without
affecting the existing functionalities.
• 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.
1) Number of Parameter
2) Types of Parameter
3) Order of Parameter
4) Kinds of Parameter
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?
• 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.
• Compiler does not find any difference in normal array parameter and a parameter array
at compile time.
• 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.
• Method overloading and method overriding both are the types of polymorphism.
• Method overriding is a runtime polymorphism because which method will get called is
decided at runtime based on the type of object.
• 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.
Aggregation
• 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
• 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.
• 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.
• In real time, Session object, Data Table object, Rows Object uses indexers to access the
values.
• 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 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 ?
• If we talk in terms of coding perspective, public fields shows abstraction and private
fields shows encapsulation.
• 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.
• 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.
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.
• 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 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?
• 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.
• Sealed class or struct are prevented from inheritance. It means Sealed classes cannot be
used as base class.
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.
• 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.]
• 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?
• Internal access modifiers are accessible from anywhere within the same assembly. We
cannot access them 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.
[If interviewer asks for rules then explain below set of rules]
• Multiple class inheritance is not possible in C# so different parts should not inherit
different base classes.
• 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.
• 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.
• StringBuilder objects are mutable so they offer better performance than string objects
when heavy string manipulation is involved.
• 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?
54. What is default underlying type to enum? Can we change its underlying type to some other
type?
• We can anytime change underlying type to any other integral datatypes like short, int16
etc depending on the size we want to store.
• 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.
• 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.
• 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.
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.
• 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.
• If the methods has return type or out parameter then the last method value get
returned from delegate.
Anonymous methods :
• Anonymous methods are nothing but methods without name. They were introduced in
C#2.0.
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.
[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]
• 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?
• 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.
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.
• Arraylist, HashTable, SortedList, Stack, Queue are few examples of non generic
collections classes.
• 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.
• 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.
• Being type safety there will not be any overhead of operations like boxing unboxing so it
helps to improve the performance.
• 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.
• 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.
• 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.
• 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.
76. What are partial methods? Anything can be asked related to rules followed during creating
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 return type must be void. Giving any other type gives compile time error.
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.
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
IComparer
• 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.
• 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.
• 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.
• 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.
• 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.
class Singleton
{
private static Singleton _instance;
private Singleton()
{
}
return _instance;
}
}
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.
• 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.
• Static fields have a single copy irrespective of number of instances of a class. They are
accessed with classname.
Constant
Readonly –
• Readonly fields are also similar to constant variables but we can change its value at
runtime through non static constructors.
• We can also have static readonly fields in which we can assign value at runtime through
static constructor but only once.