C# Interview Questions
C# Interview Questions
“The code, which is developed in .NET framework is known as managed code. This code is directly
executed by CLR with the help of managed code execution. Any language that is written in .NET
Framework is managed code”.
Unmanaged Code
The code, which is developed outside .NET framework is known as unmanaged code.
“Applications that do not run under the control of the CLR are said to be unmanaged, and certain
languages such as C++ can be used to write such applications, which, for example, access low -
level functions of the operating system. Background compatibility with the code of VB, ASP and
COM are examples of unmanaged code”.
Unmanaged code can be unmanaged source code and unmanaged compile code. Unmanaged
code is executed with the help of wrapper classes.
Boxing:
Boxing is the process of converting a value type data type to the object or to any interface data type
which is implemented by this value type. When the CLR boxes a value means when CLR is
converting a value type to Object Type, it wraps the value inside a System.Object and stores it on
the heap area in application domain.
Example:
Unboxing:
Unboxing is also a process which is used to extract the value type from the object or any
implemented interface type. Boxing may be done implicitly, but unboxing have to be explicit by
code.
Example:
The concept of boxing and unboxing underlines the C# unified view of the type system in which a
value of any type can be treated as an object.
Class and struct both are the user defined data type but have some major difference:
Struct
Class
The class is reference type in C# and it inherits from the System.Object Type.
Classes are usually used for large amounts of data.
Classes can be inherited to other class.
A class can be abstract type.
We can’t use an object of a class with using new keyword.
We can create a default constructor.
Theoretically their are some differences between Abstract Class and Interface which are listed
below:
A class can implement any number of interfaces but a subclass can at most use only one
abstract class.
An abstract class can have non-abstract methods (concrete methods) while in case of
interface all the methods has to be abstract.
An abstract class can declare or use any variables while an interface is not allowed to do so.
In an abstract class all data member or functions are private by default while in interface all
are public, we can’t change them manually.
In an abstract class we need to use abstract keyword to declare abstract methods while in an
interface we don’t need to use that.
An abstract class can’t be used for multiple inheritance while interface can be used as
multiple inheritance.
An abstract class use constructor while in an interface we don’t have any type of constructor.
To know more about the difference between Abstract Class and Interface go to the following link:
An enum is a value type with a set of related named constants often referred to as an enumerator
list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user
defined.
An enum type can be an integer (float, int, byte, double etc.). But if you used beside int it has to be
cast.
An enum is used to create numeric constants in .NET framework. All the members of enum are of
enum type. Their must be a numeric value for each enum type.
The default underlying type of the enumeration element is int. By default, the first enumerator has
the value 0, and the value of each successive enumerator is increased by 1.
1. enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
Enums in C#
Enumeration In C#
Using break statement, you can 'jump out of a loop' whereas by using continue statement, you can
'jump over one iteration' and then resume your loop execution.
1. using System;
2. using System.Collections;
3. using System.Linq;
4. using System.Text;
5.
6. namespace break_example
7. {
8. Class brk_stmt {
9. public static void main(String[] args) {
10. for (int i = 0; i <= 5; i++) {
11. if (i == 4) {
12. break;
13. }
14. Console.WriteLine("The number is " + i);
15. Console.ReadLine();
16.
17. }
18. }
19. }
20.
21. }
Output
Eg.Continue Statement
1. using System;
2. using System.Collections;
3. using System.Linq;
4. using System.Text;
5.
6. namespace continue_example
7. {
8. Class cntnu_stmt
9. {
10. public static void main(String[]
11. {
12. for (int i = 0; i <= 5; i++)
13. {
14. if (i == 4)
15. {
16. continue;
17. }
18. Console.WriteLine(“The number is "+ i);
19. Console.ReadLine();
20.
21. }
22. }
23. }
24.
25. }
26.
27.
Output
The number is 1;
The number is 2;
The number is 3;
The number is 5;
For more details follow link:
Constant (const) and Readonly (readonly) both looks like same as per the uses but they have
some differences:
Constant is known as “const” keyword in C# which is also known immutable values which are
known at compile time and do not change their values at run time like in any function or constructor
for the life of application till the application is running.
Readonly is known as “readonly” keyword in C# which is also known immutable values and are
known at compile and run time and do not change their values at run time like in any function for the
life of application till the application is running. You can assay their value by constructor when we
call constructor with “new” keyword.
We have a Test Class in which we have two variables one is readonly and another is constant.
1. class Test {
2. readonly int read = 10;
3. const int cons = 10;
4. public Test() {
5. read = 100;
6. cons = 100;
7. }
8. public void Check() {
9. Console.WriteLine("Read only : {0}", read);
10. Console.WriteLine("const : {0}", cons);
11. }
12. }
Here I was trying to change the value of both the variables in constructor but when I am trying to
change the constant it gives an error to change their value in that block which have to call at run
time.
So finally remove that line of code from class and call this Check() function like the following code
snippet:
1. class Program {
2. static void Main(string[] args) {
3. Test obj = new Test();
4. obj.Check();
5. Console.ReadLine();
6. }
7. }
8. class Test {
9. readonly int read = 10;
10. const int cons = 10;
11. public Test() {
12. read = 100;
13. }
14. public void Check() {
15. Console.WriteLine("Read only : {0}", read);
16. Console.WriteLine("const : {0}", cons);
17. }
18. }
Output:
To know more go to the following link:
In C Sharp (C#) we can have three types of parameters in a function. The parameters can be in
parameter (which is not returned back to the caller of the function), out parameter and ref parameter.
We have lots of differences in both of them.
For more details go to the following link:
Properties are members that provide a flexible mechanism to read, write or compute the values of
private fields, in other words by the property we can access private fields. In other words we can say
that a property is a return type function/method with one parameter or without a parameter. These
are always public data members. It uses methods to access and assign values to private fields
called accessors.
The get and set portions or blocks of a property are called accessors. These are useful to restrict the
accessibility of a property, the set accessor specifies that we can assign a value to a private field in a
property and without the set accessor property it is like a read-only field. By the get accessor we can
access the value of the private field, in other words it returns a single value. A Get accessor
specifies that we can access the value of a field publically.
Read/Write.
ReadOnly.
WriteOnly
Extension methods enable you to add methods to existing types without creating a new derived type,
recompiling, or otherwise modifying the original type. An extension method is a special kind of static
method, but they are called as if they were instance methods on the extended type.
An extension method is a static method of a static class, where the "this" modifier is applied to the
first parameter. The type of the first parameter will be the type that is extended.
Extension methods are only in scope when you explicitly import the namespace into your source
code with a using directive.
1. public class Class1 {
2. public string Display() {
3. return ("I m in Display");
4. }
5.
6. public string Print() {
7. return ("I m in Print");
8. }
9. }
Now we need to extend the definition of this class so m going to create a static class to create an
extinction method like:
1. public static class XX {
2. public static void NewMethod(this Class1 ob) {
3. Console.WriteLine("Hello I m extended method");
4. }
5. }
Here I just create a method that name is NewMethod with a parameter using this to define which
type of data I need to be extend, now let’s see how to use this function.
1. class Program {
2. static void Main(string[] args) {
3. Class1 ob = new Class1();
4. ob.Display();
5. ob.Print();
6. ob.NewMethod();
7. Console.ReadKey();
8. }
9. }
Extension Methods in C#
Extension Method In C#
Extension Methods in C#
Finalize:
Finalize used to free unmanaged resources those are not in use like files, database
connections in application domain and more, held by an object before that object is
destroyed.
In the Internal process it is called by Garbage Collector and can’t called manual by user code
or any service.
Finalize belongs to System.Object class.
Implement it when you have unmanaged resources in your code, and make sure that these
resources are freed when the Garbage collection happens.
Dispose:
Dispose is also used to free unmanaged resources those are not in use like files, database
connections in Application domain at any time.
Dispose explicitly it is called by manual user code.
If we need to dispose method so must implement that class by IDisposable interface.
It belongs to IDisposable interface.
Implement this when you are writing a custom class that will be used by other users.
StringBuilder and string both use to store string value but both have many differences on the bases
of instance creation and also for performance:
String:
String is an immutable object. Immutable like when we create string object in code so we cannot
modify or change that object in any operations like insert new value, replace or append any value
with existing value in string object, when we have to do some operations to change string simply it
will dispose the old value of string object and it will create new instance in memory for hold the new
value in string object like:
Note:
Performance wise string is slow because its’ create a new instance to override or change the
previous value.
StringBuilder:
System.Text.Stringbuilder is mutable object which also hold the string value, mutable means once
we create a System.Text.Stringbuilder object we can use this object for any operation like insert
value in existing string with insert functions also replace or append without creating new instance of
System.Text.Stringbuilder for every time so it’s use the previous object so it’s work fast as compare
than System.String. Let’s have an example to understand System.Text.Stringbuilder like:
Note:
C# delegates are same as pointers to functions, in C or C++. A delegate Object is a reference type
variable that use to holds the reference to a method. The reference can be changed at runtime
which is hold by an object of delegate, a delegate object can hold many functions reference which is
also known as Invocation List that refers functions in a sequence FIFO, we can new functions ref in
this list at run time by += operator and can remove by -= operator.
Delegates are especially used for implementing events and the call-back methods. All delegates are
implicitly derived from the System.Delegate class.
C# Delegates
Delegates in C#
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a
class is defined as a sealed class, the class cannot be inherited.
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the Not
Inheritable keyword serves the purpose of sealed. If a class is derived from a sealed class then the
compiler throws an error.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
1. // Sealed class
2. sealed class SealedClass
3. {
4.
5. }
Sealed Class in C#
Sealed Class in C#
A partial class is only use to splits the definition of a class in two or more classes in a same source
code file or more than one source files. You can create a class definition in multiple files but it will be
compiled as one class at run time and also when you’ll create an instance of this class so you can
access all the methods from all source file with a same object.
Partial Classes can be create in the same namespace it’s doesn’t allowed to create a partial class in
different namespace. So use “partial” keyword with all the class name which you want to bind
together with the same name of class in same namespace, let’s have an example:
Boxing and Unboxing both using for type converting but have some difference:
Boxing:
Boxing is the process of converting a value type data type to the object or to any interface data type
which is implemented by this value type. When the CLR boxes a value means when CLR converting
a value type to Object Type, it wraps the value inside a System.Object and stores it on the heap
area in application domain.
Example:
Unboxing:
Unboxing is also a process which is use to extracts the value type from the object or any
implemented interface type. Boxing may be done implicit but unboxing have to be explicit by code.
Example:
The concept of boxing and unboxing underlies the C# unified view of the type system in which a
value of any type can be treated as an object.
IEnumerable is the parent interface for all non-generic collections in System.Collections namespace
like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as
IEnumerable<T> which a parent interface of all generic collections class in
System.Collections.Generic namespace like List<> and more.
In System.Collections.Generic.IEnumerable<T> have only a single method which is
GetEnumerator() that returns an IEnumerator. IEnumerator provides the power to iterate through the
collection by exposing a Current property and Move Next and Reset methods, if we doesn’t have this
interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our
LINQ query.
Early Binding and Late Binding concepts belongs to polymorphism so let’s see first about
polymorphism:
Polymorphism is an ability to take more than one form of a function means with a same name we
can write multiple functions code in a same class or any derived class.
In Compile time polymorphism or Early Binding we will use multiple methods with same name but
different type of parameter or may be the number or parameter because of this we can perform
different-different tasks with same method name in the same class which is also known as Method
overloading.
Run Time Polymorphism or Late Binding:
Run time polymorphism also known as late binding, in Run Time polymorphism or Late Binding we
can do use same method names with same signatures means same type or same number of
parameters but not in same class because compiler doesn’t allowed that at compile time so we can
use in derived class that bind at run time when a child class or derived class object will instantiated
that’s way we says that Late Binding. For that we have to create my parent class functions as partial
and in driver or child class as override functions with override keyword.
IEnumerable:
Is the parent interface for all non-generic collections in System.Collections namespace like ArrayList,
HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable<T>
which a parent interface of all generic collections class in System.Collections.Generic namespace
like List<> and more.
IQueryable:
As per MSDN IQueryable interface is intended for implementation by query providers. It is only
supposed to be implemented by providers that also implement IQueryable<T>. If the provider does
not also implement IQueryable<T>, the standard query operators cannot be used on the provider's
data source.
The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the
results of that query can be enumerated. Enumeration causes the expression tree associated with
an IQueryable object to be executed. The definition of "executing an expression tree" is specific to a
query provider. For example, it may involve translating the expression tree to an appropriate query
language for the underlying data source. Queries that do not return enumerable results are executed
when the Execute method is called.
IEnumerable vs IQuerable
IEnumerable Vs IQueryable
we can use multiple Catches block with every try but when any Exceptions is throw by debugger so
every catches match this exception type with their signature and catch the exception by any single
catch block so that means we can use multiple catches blocks but only one can executed at once
like:
1. using System;
2. class MyClient {
3. public static void Main() {
4. int x = 0;
5. int div = 0;
6. try {
7. div = 100 / x;
8. Console.WriteLine("Not executed line");
9. } catch (DivideByZeroException de) {
10. Console.WriteLine("DivideByZeroException");
11. } catch (Exception ee) {
12. Console.WriteLine("Exception");
13. } finally {
14. Console.WriteLine("Finally Block");
15. }
16. Console.WriteLine("Result is {0}", div);
17. }
18. }
Exception Handling in C#
1. Ensures a class has only one instance and provides a global point of access to it.
2. A singleton is a class that only allows a single instance of itself to be created, and usually
gives simple access to that instance.
3. Most commonly, singletons don't allow any parameters to be specified when creating the
instance, since a second request of an instance with a different parameter could be
problematic! (If the same instance should be accessed for all requests with the same
parameter then the factory pattern is more appropriate.)
4. There are various ways to implement the Singleton Pattern in C#. The following are the
common characteristics of a Singleton Pattern.
1. namespace Singleton {
2. class Program {
3. static void Main(string[] args) {
4. Calculate.Instance.ValueOne = 10.5;
5. Calculate.Instance.ValueTwo = 5.5;
6. Console.WriteLine("Addition : " + Calculate.Instance.Addition());
7. Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
8. Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication()
);
9. Console.WriteLine("Division : " + Calculate.Instance.Division());
10.
11. Console.WriteLine("\n----------------------\n");
12.
13. Calculate.Instance.ValueTwo = 10.5;
14. Console.WriteLine("Addition : " + Calculate.Instance.Addition());
15. Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
16. Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication()
);
17. Console.WriteLine("Division : " + Calculate.Instance.Division());
18.
19. Console.ReadLine();
20. }
21. }
22.
23. public sealed class Calculate {
24. private Calculate() {}
25. private static Calculate instance = null;
26. public static Calculate Instance {
27. get {
28. if (instance == null) {
29. instance = new Calculate();
30. }
31. return instance;
32. }
33. }
34.
35. public double ValueOne {
36. get;
37. set;
38. }
39. public double ValueTwo {
40. get;
41. set;
42. }
43.
44. public double Addition() {
45. return ValueOne + ValueTwo;
46. }
47.
48. public double Subtraction() {
49. return ValueOne - ValueTwo;
50. }
51.
52. public double Multiplication() {
53. return ValueOne * ValueTwo;
54. }
55.
56. public double Division() {
57. return ValueOne / ValueTwo;
58. }
59. }
60. }
The basic difference is that the Throw exception overwrites the stack trace and this makes it hard to
find the original code line number that has thrown the exception.
Throw basically retains the stack information and adds to the stack information in the exception that
it is thrown.
Let us see what it means rather speaking so many words to better understand the differences. I am
using a console application to easily test and see how the usage of the two differ in their
functionality.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5.
6. namespace TestingThrowExceptions {
7. class Program {
8. public void ExceptionMethod() {
9. throw new Exception("Original Exception occurred in ExceptionMethod");
10.
11. }
12.
13. static void Main(string[] args) {
14. Program p = new Program();
15. try {
16. p.ExceptionMethod();
17. } catch (Exception ex) {
18.
19. throw ex;
20. }
21. }
22. }
23. }
Now run the code by pressing the F5 key of the keyboard and see what happens. It returns an
exception and look at the stack trace:
Indexer allows classes to be used in more intuitive manner. C# introduces a new concept known as
Indexers which are used for treating an object as an array. The indexers are usually known as smart
arrays in C#. They are not essential part of object-oriented programming.
An indexer, also called an indexed property, is a class property that allows you to access a member
variable of a class using the features of an array.
Defining an indexer allows you to create classes that act like virtual arrays. Instances of that class
can be accessed using the [] array access operator.
Creating an Indexer
1. < modifier > <
2. return type > this[argument list] {
3. get {
4. // your get block code
5. }
6.
7. set {
8. // your set block code
9. }
10. }
<modifier>
<return type>
Indexers in C#
INDEXER in C#
Delegate can invoke only one method reference has been encapsulated into the delegate.it is
possible for certain delegate to hold and invoke multiple methods such delegate called multicast
delegates.multicast delegates also know as combinable delegates, must satisfy the following
conditions:
The return type of the delegate must be void. None of the parameters of the delegate type
can be delegate type can be declared as output parameters using out keywords.
Multicast delegate instance that created by combining two delegates, the invocation list is
formed by concatenating the invocation list of two operand of the addition operation.
Delegates are invoked in the order they are added.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. delegate void MDelegate();
6. class DM {
7. static public void Display() {
8. Console.WriteLine("Meerut");
9. }
10. static public void print() {
11. Console.WriteLine("Roorkee");
12. }
13. }
14. class MTest {
15. public static void Main() {
16. MDelegate m1 = new MDelegate(DM.Display);
17. MDelegate m2 = new MDelegate(DM.print);
18. MDelegate m3 = m1 + m2;
19. MDelegate m4 = m2 + m1;
20. MDelegate m5 = m3 - m2;
21. m3();
22. m4();
23. m5();
24. }
25. }
Both the == Operator and the Equals() method are used to compare two value type data items or
reference type data items. The Equality Operator (==) is the comparison operator and the Equals()
method compares the contents of a string. The == Operator compares the reference identity while
the Equals() method compares only contents. Let’s see with some examples.
In this example we assigned a string variable to another variable. A string is a reference type and in
the following example, a string variable is assigned to another string variable so they are referring to
the same identity in the heap and both have the same content so you get True output for both the ==
Operator and the Equals() method.
1. using System;
2. namespace ComparisionExample {
3. class Program {
4. static void Main(string[] args) {
5. string name = "sandeep";
6. string myName = name;
7. Console.WriteLine("== operator result is {0}", name == myName);
8. Console.WriteLine("Equals method result is {0}", name.Equals(myName));
9. Console.ReadKey();
10. }
11. }
12. }
A nullable Type is a data type is that contain the defined data type or the value of null.
You should note here that here variable datatype has been given and then only it can be used.
Declaration:
Any DataType can be declared nullable type with the help of operator "?".
1. int? i = null;
As discussed in previous section "var" is not compatible with this Nullable Type.
1. var? i = null;
1. var i = 4;
Generics allow you to delay the specification of the data type of programming elements in a class or
a method, until it is actually used in the program. In other words, generics allow you to write a class
or method that can work with any data type.
You write the specifications for the class or the method, with substitute parameters for data types.
When the compiler encounters a constructor for the class or a function call for the method, it
generates code to handle the specific data type.
Generic classes and methods combine reusability, type safety and efficiency in a way that their non-
generic counterparts cannot. Generics are most frequently used with collections and the methods
that operate on them. Version 2.0 of the .NET Framework class library provides a new namespace,
System.Collections.Generic, that contains several new generic-based collection classes. It is
recommended that all applications that target the .NET Framework 2.0 and later use the new generic
collection classes instead of the older non-generic counterparts such as ArrayList.
Features of Generics
Introduction to Generics in C#
Generics in C#
Access modifiers are keywords used to specify the declared accessibility of a member or a type.
Access modifiers are an integral part of object-oriented programming. They support the concept of
encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define
who does or doesn't have access to certain features.
When a method is declared as a virtual method in a base class then that method can be defined in a
base class and it is optional for the derived class to override that method. The overriding method
also provides more than one form for a method. Hence it is also an example for polymorphism.
When a method is declared as a virtual method in a base class and that method has the same
definition in a derived class then there is no need to override it in the derived class. But when a
virtual method has a different definition in the base class and the derived class then there is a need
to override it in the derived class.
When a virtual method is invoked, the run-time type of the object is checked for an overriding
member. The overriding member in the most derived class is called, which might be the original
member, if no derived class has overridden the member.
Virtual Method
Virtual Method in C#
Anonymous types allow us to create new type without defining them. This is way to defining read
only properties into a single object without having to define type explicitly. Here Type is generating
by the compiler and it is accessible only for the current block of code. The type of properties is also
inferred by the compiler.
We can create anonymous types by using “new” keyword together with the object initializer.
Example
1. var anonymousData = new
2. {
3. ForeName = "Jignesh",
4. SurName = "Trivedi"
5. };
6. Console.WriteLine("First Name : " + anonymousData.ForeName);
Anonymous types are also used with the "Select" clause of LINQ query expression to return subset
of properties.
Example
If Any object collection having properties called FirstName , LastName, DOB etc. and you want only
FirstName and LastName after the Querying the data then.
1. class MyData {
2. public string FirstName {
3. get;
4. set;
5. }
6. public string LastName {
7. get;
8. set;
9. }
10. public DateTime DOB {
11. get;
12. set;
13. }
14. public string MiddleName {
15. get;
16. set;
17. }
18. }
19. static void Main(string[] args) {
20. // Create Dummy Data to fill Collection.
21. List < MyData > data = new List < MyData > ();
22. data.Add(new MyData {
23. FirstName = "Jignesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTi
me(1990, 12, 30)
24. });
25. data.Add(new MyData {
26. FirstName = "Tejas", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime
(1995, 11, 6)
27. });
28. data.Add(new MyData {
29. FirstName = "Rakesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTim
e(1993, 10, 8)
30. });
31. data.Add(new MyData {
32. FirstName = "Amit", LastName = "Vyas", MiddleName = "P", DOB = newDateTime(1983
, 6, 15)
33. });
34. data.Add(new MyData {
35. FirstName = "Yash", LastName = "Pandiya", MiddleName = "K", DOB = newDateTime(1
988, 7, 20)
36. });
37. }
38. var anonymousData = from pl in data
39. select new {
40. pl.FirstName, pl.LastName
41. };
42. foreach(var m in anonymousData) {
43. Console.WriteLine("Name : " + m.FirstName + " " + m.LastName);
44. }
45. }
Anonymous Types in C#
Return Anonymous Type in C#