0% found this document useful (0 votes)
16 views166 pages

C# Interview Questions

This document contains a comprehensive list of C# interview questions categorized into various levels of difficulty, including basic, intermediate, and advanced topics. It covers a wide range of subjects such as method overloading, reflection, delegates, multithreading, and design patterns, among others. Additionally, it includes coding problems and explanations of key concepts relevant to C# programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views166 pages

C# Interview Questions

This document contains a comprehensive list of C# interview questions categorized into various levels of difficulty, including basic, intermediate, and advanced topics. It covers a wide range of subjects such as method overloading, reflection, delegates, multithreading, and design patterns, among others. Additionally, it includes coding problems and explanations of key concepts relevant to C# programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

C# Interview Questions

Contents
18. What is the difference between late binding and early binding in C#?........................................18
19. What are the different ways in which a method can be Overloaded in C#?................................18
20. What is Reflection in C#?.............................................................................................................18
21. What is the difference between constant and read-only in C#?..................................................18
26. What is the difference between to dispose and finalize methods in C#?....................................20
27. What are delegates in C#?...........................................................................................................20
29. What is the Constructor Chaining in C#?.....................................................................................20
33. What is a Virtual Method in C#?..................................................................................................20
34. What is Multithreading with .NET?..............................................................................................20
37. Why a private virtual method cannot be overridden in C#?........................................................21
38. What is File Handling in C#?........................................................................................................21
39. List down the commonly used types of exceptions?...................................................................22
40. What is the difference between “is” and “as” operators in C#?.................................................22
41. What is Singleton design pattern in C#?......................................................................................23
42. How to implement a singleton design pattern in C#?..................................................................23
43. What is tuple in C#?.....................................................................................................................23
44. What are Events?.........................................................................................................................23
47. Write a Features of Generics in C#?.............................................................................................24
48. Difference between SortedList and SortedDictionary in C#.........................................................25
49. What are namespaces in C#?.......................................................................................................25
50. Who can be the members of namespaces in C#?.......................................................................26
Q7. List down the access modifiers available in C#............................................................................26
Q8. List down the different IDE’s Provided by Microsoft for C# Development..................................26
Q9. Distinguish between Continue and Break Statement?................................................................26
Q10. What are the different approaches of passing parameters to a method?................................27
Intermediate level C# Interview Questions................................................................28
Q11. Distinguish between finally and finalize blocks?.......................................................................28
Q12. What is Managed or Unmanaged Code?...................................................................................28
Q13. What is an Object?....................................................................................................................28
Q15. Define an abstract class?...........................................................................................................28
Q16. Define sealed classes in C#?......................................................................................................28
Q17. Define a Partial class?................................................................................................................28
Q18. List down the fundamental OOP concepts?..............................................................................28
Q19. Explain the process of inheriting a class into another class?.....................................................29
Q20. Define method overloading in C#?............................................................................................29
Q21. List the differences between method overriding and method overloading?............................29
Q22. Explain StreamReader/StreamWriter class?.............................................................................29
Q23. What is an Interface?................................................................................................................30
Q24. Distinguish between a class and struct?....................................................................................30
Q25. List the difference between the Virtual method and the Abstract method?............................30
Q26. Illustrate Namespaces in C#?....................................................................................................30
Q27. Define using statement in C#?..................................................................................................30
Q28. Define an Escape Sequence, Name few strings in Escape Sequence?.......................................30
Q29. Define Boxing and Unboxing in C#?..........................................................................................31
Q31. Define a Jagged Array in C#?...............................................................................32
Q32. Distinguish between Array and Arraylist in C#?........................................................................32
Q33. Define Collections?....................................................................................................................33
Q34. Write a short note on Interface?...............................................................................................33
Advanced Level............................................................................................................................33
Q35. Illustrate Serialization?..............................................................................................................33
Q36. Define Parsing? Explain how to Parse a DateTime String?........................................................34
Q37. Define Delegate?.......................................................................................................................34
Q38. Distinguish between [Link] and [Link] classes?............................34
Q39. Illustrate the differences between the [Link]() and [Link]()?.....35
Q40. Write the Syntax for catching an exception in C#?....................................................................35
Q41. Explain about generics in C#.NET?............................................................................................35
Q43. Define C# I/O classes? List the commonly used classes?...........................................................35
Q44. Define thread? Explain about Multithreading?.........................................................................36
Q45. What are Events?........................................................................................................36
Q46. Explain Synchronous and Asynchronous Operations?...........................37
Q47. Explain Async and Await?.......................................................................................37
Q48. Explain Deadlock?.......................................................................................................37
Q49. Illustrate Race Condition?......................................................................................38
Q50. What is Thread Pooling?...........................................................................................................38
1. What is C#?....................................................................................................................................38
2. Explain types of comment in C# with examples.............................................................................38
3. Can multiple catch blocks be executed?........................................................................................39
4. What is the difference between public, static, and void?..............................................................39
5. What is an object?.........................................................................................................................39
6. Define Constructors.......................................................................................................................39
7. What is Jagged Arrays?..................................................................................................................39
8. What is the difference between ref & out parameters?................................................................40
9. What is the use of ‘using’ statement in C#?...................................................................................40
10. What is serialization?...................................................................................................................40
11. Can we use “this” command within a static method?.................................................................40
12. What is the difference between constants and read-only?.........................................................40
C# Advanced Interview Questions for 3/5/10 Years Experience...........................................................40
13. What is an interface class? Give one example of it......................................................................40
14. What are value types and reference types?................................................................................41
15. What are Custom Control and User Control?..............................................................................41
16. What are sealed classes in C#?....................................................................................................42
17. What is method overloading?......................................................................................................42
18. What is the difference between Array and Arraylist?..................................................................42
19. Can a private virtual method can be overridden?........................................................................43
20. Describe the accessibility modifier “protected internal”.............................................................43
21. What are the differences between [Link] and [Link] classes?.........43
22. What’s the difference between the [Link]() and [Link]() ?...........43
23. How can we sort the elements of the Array in descending order?..............................................44
24. Write down the C# syntax to catch an exception........................................................................44
25. What’s the difference between an interface and abstract class?...............................................44
27. What are circular references?.....................................................................................................44
28. What are generics in C#.NET?......................................................................................................44
29. What is an object pool in .NET?...................................................................................................44
30. List down the commonly used types of exceptions in .net........................................................45
31. What are Custom Exceptions?....................................................................................................45
32. What are delegates?....................................................................................................................45
33. How do you inherit a class into other class in C#?......................................................................45
34. What is the base class in .net from which all the classes are derived from?..............................45
35. What is the difference between method overriding and method overloading?........................45
36. What are the different ways a method can be overloaded?.......................................................45
37. Why can’t you specify the accessibility modifier for methods inside the interface?.................46
38. How can we set the class to be inherited, but prevent the method from being over-ridden?....46
39. What happens if the inherited interfaces have conflicting method names?.............................46
40. What is the difference between a Struct and a Class?................................................................46
41. How to use nullable types in .Net?..............................................................................................46
42. How we can create an array with non-default values?................................................................46
43. What is difference between “is” and “as” operators in c#?.........................................................46
44. What’s a multicast delegate?.......................................................................................................47
45. What are indexers in C# .NET?.....................................................................................................47
46. What is difference between the “throw” and “throw ex” in .NET?.............................................47
47. What are C# attributes and its significance?................................................................................47
48. How to implement a singleton design pattern in C#?................................................................47
49. What is the difference between directcast and ctype?...............................................................47
50. Is C# code is managed or unmanaged code?.............................................................................47
51. What is Console application?......................................................................................................48
52. Give an example of removing an element from the queue........................................................48
2. What is Common Language Runtime (CLR)?....................................................48
3. What is garbage collection in C#?.........................................................................49
4. What are the types of classes in C#?...................................................................50
5. What is a managed and unmanaged code?......................................................50
6. What is the difference between an abstract class and an interface?............................................51
7. What are the differences between ref and out keywords?....................51
8. What are extension methods in C#?....................................................................52
9. What are Generics in C#?..............................................................................................................53
10. What is the difference between an Array and ArrayList in C#?...................................................54
11. What is inheritance? Does C# support multiple inheritance?...........54
C# Advanced Interview Questions..................................................................................57
12. What is Boxing and Unboxing in C#?...........................................................................................57
13. What are Properties in C#?..........................................................................................................57
14. What are partial classes in C#?....................................................................................................57
15. What is the difference between late binding and early binding in C#?........................................58
16. What are the Arrays in C#?.....................................................................................58
17. What are Indexers in C#?.........................................................................................59
18. Difference between the Equality Operator (==) and Equals()
Method in C#?..........................................................................................................................60
19. What are the different ways in which a method can be Overloaded
in C#?............................................................................................................................................60
20. What is Reflection in C#?.........................................................................................61
21. What is the difference between constant and readonly in C#?........61
22. What is the difference between String and StringBuilder in C#?.................................................63
C# Coding Problems.................................................................................................................63
23. Write a program in C# Sharp to reverse a string?....................................63
24. Write a program in C# Sharp to reverse the order of the given
words?...........................................................................................................................................64
25. Write a program in C# Sharp to find if a given string is palindrome
or not?...........................................................................................................................................64
26. Write a C# program to find the substring from a given string........65
27. Write a C# program to find if a positive integer is prime or not?...65
1. What is a Datatype?............................................................................................................80
2. What are Nullable types?..................................................................................................80
3. What is (??) operator in C#?............................................................................................81
4. How to check that a nullable variable is having value?.......................................81
5. What are the differences between Object and Var?..............................................81
6. What is the ref keyword in C#?......................................................................................81
7. What is the params keyword in C#?............................................................................81
8. What do you mean by operators in C#?.....................................................................81
9. What are the different types of operators in C#?...................................................82
10. What is ternary operator in C#?..................................................................................82
11. What is the static keyword mean in C#?.................................................................82
12. What do you mean by Typecasting in C#?.............................................................82
13. What are the different types of casting in C#?.....................................................83
14. What is an Out keyword in C#?...................................................................................83
15. Can out and ref be used for overloading as the different signature of
method?.........................................................................................................................................83
16. What do you mean by value type and reference type?.....................................83
17. What is a safe and unsafe code in C#?....................................................................83
18. What is boxing and unboxing in C#?.........................................................................84
19. What is upcasting and downcasting?........................................................................84
20. What do you mean by static members?...................................................................84
21. What is the base class in .NET framework from which all the classes have
been developed?........................................................................................................................84
22. What is a static class?......................................................................................................84
23. When to use a static class?...........................................................................................85
24. What are sealed classes in C#?...................................................................................85
25. Can multiple catch blocks be implemented?..........................................................85
26. What is an object pool in .NET?....................................................................................85
27. What do you mean by partial method?.....................................................................85
28. What are the different ways a method can be overloaded?............................85
29. What is serialization and its main purpose in C#?...............................................86
30. What is reflection in C#?................................................................................................86
31. When should reflection be used?................................................................................86
32. What do you mean by exceptions in C#?................................................................86
33. What is the role of [Link] class?..........................................................86
34. What is exception handling?.........................................................................................87
35. What are the various types of serialization?..........................................................87
36. What are Delegates?........................................................................................................87
37. What is Polymorphism in C#?.......................................................................................87
38. What are the uses of delegates in C#?....................................................................87
39. What is the property in C#?..........................................................................................87
40. What are the uses of the property?...........................................................................88
41. What is the difference between “as” and “is” operators in C#?...................88
43. What is an indexer in C#?..............................................................................................88
44. How encapsulation is implemented in C#?.............................................................88
44. What are collections in C#?...........................................................................................88
45. What are Generics in C#?..............................................................................................88
46. What is Anonymous type in C#?.................................................................................89
47. Can you briefly explain Thread Pooling in C#?.....................................................89
48. What is Multithreading in C#?......................................................................................89
49. What are the different states of a Thread in C#?................................................89
50. How can the singleton design pattern in C# be used?......................................89
51. What are the different types of decision-making statements in C#?..........90
52. Which one is better/faster, switch or if-else-if statements, and why?.........90
53. What is the goto statement?.......................................................................................................90
54. What is the return statement in C#?...........................................................................................90
55. What is the jump statement in C#?.............................................................................................90
56. What does the throw statement do?..........................................................................90
57. What do you mean by an array and what are the different types of the array in C#?.................91
58. What is a multi-dimensional array?............................................................................91
59. What is a jagged array?................................................................................................................91
60. What do you mean by an object in C#?.......................................................................................91
61. What is a constructor?.................................................................................................................91
62. Why does the static constructor have no parameter?.......................................91
63. Why can you have only one static constructor?...................................................92
64. What is a destructor in C#?..........................................................................................................92
65. What purpose does the “using” statement serve in C#?.............................................................92
66. What is the purpose of an access modifier?...........................................................92
67. Can destructors have access modifiers?..................................................................92
68. What is enum and when should it be used?...........................................................92
69. What is the difference between class and structure?.........................................93
70. What is the difference between direct cast and ctype?...............................................................93
71. When should you use Async and Await?.....................................................................................93
72. What is Managed and Unmanaged code?...................................................................................93
73. Explain Namespaces in C#?..........................................................................................93
74. What is a Deadlock?..........................................................................................................94
FAQs Related to C#......................................................................................................................94
1. What is the difference between Public, Static, void?......................................95
2. What is C# also mention some features of C#....................................................95
3. Please elaborate on the reason why we use C#.................................................95
4. What are the advantages of C#?.................................................................................96
5. What are the different types of comments in C#?............................................96
6. Elaborate the code compilation process in C#?..................................................96
7. List down the available access modifier in the C#?..........................................96
8. Mention the different IDE’s provided by Microsoft?.........................................96
9. Distinguish between continue and break statement?.....................................96
10. What are the different approaches to pass the parameter to a
function?..........................................................................................................................................97
11. Distinguish between finally finalize block?.........................................................97
12. What is managed and unmanaged code?........................................................................................97
13. Differentiate between class and object?.........................................................................................97
14. What is an abstract class?................................................................................................................97
15. What is a sealed class?....................................................................................................................98
16. Elaborate the fundamentals of oop?...............................................................................................98
17. How can we inherit one class from another class?..........................................................................98
18. What is method overloading?..........................................................................................................98
19. Differentiate between method overloading and overriding?...................98
20. Define an interface?.........................................................................................................99
21. Distinguish between class and struct?..................................................................99
22. Differentiate between virtual and abstract method?....................................99
23. Illustrate the namespace in C#?................................................................................99
24. Define the 'using' statement?...................................................................................100
25. Define boxing and unboxing?....................................................................................100
26. What is an array?.............................................................................................................100
27. What is a jagged array?.................................................................................................................100
28. Distinguish between array and array list?......................................................................................100
29. What is collection?........................................................................................................................101
30. Illustrate the serialization?............................................................................................................101
31. What is parsing?............................................................................................................................101
33. Distinguish between string and StringBuilder?..............................................................................101
34. What is LINQ?................................................................................................................................102
35. What is garbage collection?...........................................................................................................102
36. Please elaborate on the following acronyms in .NET stand for IL, CIL, MSIL, CLI, and JIT?............102
37. Distinguish between heap and stack?............................................................................................103
38. Please elaborate on inheritance and why we use it?.....................................................................103
39. Distinguish between an Interface and an Abstract Class?.............................................................103
40. Differentiate between [Link]() and
[Link]()?...........................................................................................................104
41. Differentiate between “is” and “as” operator?.............................................104
42. Differentiate between Equality Operator (==) and Equals () Method?
.............................................................................................................................................................104
43. Elaborate the indexer?..................................................................................................104
44. Differentiate through exception and through clause?...............................104
45. Can we use multiple catch block execution?....................................................105
46. Explain the usage of the extension method?...................................................105
47. Can we inherit private class members to the derived class?.................105
48. Elaborate enum?...............................................................................................................105
49. Explain Get and Set in properties?........................................................................105
50. Elaborate deadlock?.......................................................................................................106
1. What is the difference between Public, Static, void?..................................................107
2. What is C# also mention some features of C#.............................................................107
3. Please elaborate on the reason why we use C#...........................................................108
4. What are the advantages of C#?.......................................................................................108
5. What are the different types of comments in C#?.......................................................108
6. Elaborate the code compilation process in C#?...........................................................109
7. List down the available access modifier in the C#?....................................................109
8. Mention the different IDE’s provided by Microsoft?.....................................................109
9. Distinguish between continue and break statement?................................................109
10. What are the different approaches to pass the parameter to a function?........109
12. What is managed and unmanaged code?....................................................................109
13. Differentiate between class and object?.......................................................................110
14. What is an abstract class?..................................................................................................110
15. What is a sealed class?.......................................................................................................110
16. Elaborate the fundamentals of oop?..............................................................................110
17. How can we inherit one class from another class?....................................................111
18. What is method overloading?...........................................................................................111
19. Differentiate between method overloading and overriding?.................................111
20. Define an interface?.............................................................................................................111
21. Distinguish between class and struct?...........................................................................111
22. Differentiate between virtual and abstract method?................................................112
23. Illustrate the namespace in C#?......................................................................................112
24. Define the 'using' statement?...........................................................................................112
25. Define boxing and unboxing?...........................................................................................113
26. What is an array?..................................................................................................................113
27. What is a jagged array?......................................................................................................113
28. Distinguish between array and array list?....................................................................113
29. What is collection?................................................................................................................113
30. Illustrate the serialization?.................................................................................................114
31. What is parsing?....................................................................................................................114
32. Explain about delegate?.....................................................................................................114
33. Distinguish between string and StringBuilder?...........................................................114
34. What is LINQ?..........................................................................................................................115
35. What is garbage collection?...............................................................................................115
36. Please elaborate on the following acronyms in .NET stand for IL, CIL, MSIL, CLI,
and JIT?.............................................................................................................................................115
37. Distinguish between heap and stack?...........................................................................116
38. Please elaborate on inheritance and why we use it?................................................116
39. Distinguish between an Interface and an Abstract Class?......................................116
40. Differentiate between [Link]() and [Link]()?.....117
41. Differentiate between “is” and “as” operator?...........................................................117
42. Differentiate between Equality Operator (==) and Equals () Method?..............117
43. Elaborate the indexer?........................................................................................................117
44. Differentiate through exception and through clause?..............................................118
45. Can we use multiple catch block execution?...............................................................118
46. Explain the usage of the extension method?..............................................................118
47. Can we inherit private class members to the derived class?................................118
48. Elaborate enum?....................................................................................................................118
49. Explain Get and Set in properties?..................................................................................118
50. Elaborate deadlock?.............................................................................................................119
1. What is a class?........................................................................................................................119
2. What are the main concepts of object-oriented programming?.............................120
3. Explain Encapsulation............................................................................................................120
4. What is abstraction?...............................................................................................................122
START YOUR DEVELOPER CAREER TODAY...........................................................................122
5. What is polymorphism?.........................................................................................................122
6. What is Inheritance in C#?...................................................................................................124
7. What is an object?...................................................................................................................125
8. What is a constructor, and what are its different types?...........................................126
9. What is a destructor in C#?.................................................................................................128
10. Is C# code managed or unmanaged code?.................................................................128
11. What are value types and reference types?................................................................128
12. What are namespaces, and is that compulsory?.......................................................129
13. Explain types of comments in c# with examples......................................................130
14. What is an interface? Give an example.........................................................................131
15. How to implement multiple interfaces with the same method name in the
same class?.....................................................................................................................................132
16. What is the virtual method, and how is it different from the abstract method?
.............................................................................................................................................................133
17. What is method overloading and method overriding?.............................................135
18. What is the static keyword?...............................................................................................135
19. Can we use “this” with the static class?.......................................................................136
20. What is the difference between constants and read-only?....................................136
21. What is the difference between string and string builder in C#?........................138
22. Explain the “continue” and “break” statement.............................................................................139
23. What are boxing and unboxing?....................................................................................................141
24. What is a sealed class?..................................................................................................................142
25. What is a partial class?..................................................................................................................143
26. What is enum?...............................................................................................................................143
27. What is dependency injection, and how can it be achieved?........................................................143
28. The “using” statement...................................................................................................................144
29. What are the access modifiers? Explain each type........................................................................144
30. What are delegates?......................................................................................................................145
31. What are the different types of delegates?...................................................................................146
32. What is an array? Explain Single and multi-dimensional arrays.....................................................147
33. What is the difference between the [Link]() and [Link]() ?............147
34. What is the difference between array and arraylist?.....................................................................147
35. What is a jagged array in C#?.........................................................................................................148
36. What is the difference between struct and class?.........................................................................149
37. What is the difference between throw and throw ex?..................................................................150
38. Explain the difference between finally and finalize block?............................................................150
39. Explain var and dynamic................................................................................................................150
40. What are Anonymous types in C#?................................................................................................151
41. What is multithreading, and what are its different states?...........................................................152
42. How is exception handling done in C#?.........................................................................................153
43. What are the custom exceptions?.................................................................................................154
44. What is LINQ in C#?.......................................................................................................................155
45. What is serialization?.....................................................................................................................155
46. What are generics in c#?...............................................................................................................156
47. What is reflection?.........................................................................................................................157
48. How to use nullable types?............................................................................................................158
49. Which is the parent class of all classes which we create in C#?.....................................................158
50. Explain code compilation in C#......................................................................................................158

1. What is C#?
C# is an object-oriented, modern programming language that was created by
Microsoft. It runs on the .NET Framework.

C# is very close to C/C++ and Java programming languages. The language is


proposed to be a simple, modern, general-purpose, object-oriented programming
language. The language is used for creating software components.

2. What is Common Language Runtime (CLR)?


CLR is the basic and Virtual Machine component of the .NET Framework.

- It is the run-time environment in the .NET Framework that runs the codes and
helps in making the development process easier by providing various
services such as remoting, thread management, type-safety, memory
management, robustness, etc. Basically, it is responsible for managing the
execution of .NET programs regardless of any .NET programming language.
- It also helps in the management of code, as code that targets the runtime is
known as the Managed Code, and code that doesn’t target to runtime is
known as Unmanaged code. To read more, refer to the article: Common
Language Runtime.

3. What are indexers in C# .NET?


Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed in the same
way as an array. To read more, refer to the article: C# indexers

5. What is the JIT compiler process?


Just-In-Time compiler(JIT) is a part of Common Language Runtime (CLR) in .NET which is responsible
for managing the execution of .NET programs regardless of any .NET programming language. A
language-specific compiler converts the source code to the intermediate language. This intermediate
language is then converted into the machine code by the Just-In-Time (JIT) compiler. This machine code
is specific to the computer environment that the JIT compiler runs on. To read more, refer to the
article: What is Just-In-Time(JIT) Compiler in .NET?

6. What is garbage collection in C#?


Automatic memory management is made possible by Garbage Collection in .NET Framework. When a
class object is created at runtime, certain memory space is allocated to it in the heap memory. However,
after all the actions related to the object are completed in the program, the memory space allocated to it is
a waste as it cannot be used. In this case, garbage collection is very useful as it automatically releases
the memory space after it is no longer required.
Garbage collection will always work on Managed Heap, and internally it has an Engine which is known as
the Optimization Engine. Garbage Collection occurs if at least one of multiple conditions is satisfied.
These conditions are given as follows:
 If the system has low physical memory, then garbage collection is necessary.
 If the memory allocated to various objects in the heap memory exceeds a pre-set threshold, then
garbage collection occurs.
 If the [Link] method is called, then garbage collection occurs. However, this method is only
called under unusual situations as normally garbage collector runs automatically.
 To read more, refer to the article: Garbage collection in C#.

7. What are the types of classes in C#?


 Abstract class
 Partial class
 Sealed class
 Static class

8. What is the difference between C# abstract class and an interface?


Abstract Class Interface

It contains both declaration and definition parts. It contains only a declaration part.

Multiple inheritance is not achieved by an


abstract class. Multiple inheritance is achieved by the interface.

It does not contain a constructor.

It contains a constructor.

It can contain static members. It does not contain static members.

It can contain different types of access modifiers It only contains public access modifier because
like public, private, protected, etc. everything in the interface is public.

The performance of the interface is slow because


it requires time to search the actual method in the
The performance of an abstract class is fast. corresponding class.

It is used to implement the peripheral abilities of


It is used to implement the core identity of class. the class.

A class can only use one abstract class. A class can use multiple interfaces.

If many implementations are of the same kind


and use common behavior, then it is superior to If many implementations only share methods,
use an abstract class. then it is superior to use Interface.
Abstract Class Interface

An abstract class can contain methods, fields,


constants, etc. The interface can only contain methods.

It can be fully, partially, interface or not


implemented. It should be fully implemented.

9. What are extension methods in C#?


In C#, the extension method concept allows you to add new methods in the existing class or in the
structure without modifying the source code of the original type, and you do not require any kind of special
permission from the original type and there is no need to re-compile the original type. It is introduced in

C# 3.0. To read more, refer to the article: Extension methods in C#

10. What is inheritance? Does C# support multiple inheritance?


Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in C# by
which one class is allowed to inherit the features(fields and methods) of another class.

 Super Class: The class whose features are inherited is known as superclass(or a base class
or a parent class).
 Sub Class: The class that inherits the other class is known as a subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition
to the superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.

C# does not support multiple class inheritance . To read more, refer to the article: Inheritance
in C#
11. What is Managed or Unmanaged Code?

A code that is written to aimed to get the services of the managed runtime environment execution like
CLR(Common Language Runtime) in .NET Framework is known as Managed Code. It is always
implemented by the managed runtime environment instead of directly executed by the operating system.
The managed runtime environment provides different types of services like garbage collection, type
checking, exception handling, bounds checking, etc. to code automatically without the interference of the
programmer. It also provides memory allocation, type safety, etc to the code. The application is written in
the languages like Java, C#, [Link], etc. is always aimed at runtime environment services to manage the
execution, and the code written in these types of languages is known as managed code.
A code that is directly executed by the operating system is known as Unmanaged code. It is always
aimed at the processor architecture and depends upon computer architecture. When this code is
compiled it always tends to get a specific architecture and always runs on that platform, in other words,
whenever you want to execute the same code for the different architecture you have to recompile that
code again according to that architecture. It always compiles to the native code that is specific to the

architecture. To read more, refer to the article: Managed and Unmanaged code

12. What is the difference between a struct and a class in C#?

A class is a user-defined blueprint or prototype from which objects are created. Basically, a class
combines the fields and methods(member function which defines actions) into a single unit.
A structure is a collection of variables of different data types under a single unit. It is almost similar to
a class because both are user-defined data types and both hold a bunch of different data types. To
read more, refer to the article: struct and class in C#

13. What is enum in C#?


Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values
to integral constants, which make a program easy to read and maintain. For example, the 4 suits in a
deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an
enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of
the week, colors, directions, etc.). The main objective of enum is to define our own data
types(Enumerated Data Types). Enumeration is declared using the enum keyword directly inside a

namespace, class, or structure. To read more, refer to the article: Enum in C#

14. What is the difference between ref and out keywords?

The ref is a keyword in C# which is used for passing the arguments by a reference. Or we can say that if
any changes made in this argument in the method will reflect in that variable when the control return to
the calling method. The ref parameter does not pass the property.

The out is a keyword in C# which is used for passing the arguments to methods as a reference type. It is
generally used when a method returns multiple values. The out parameter does not pass the property. To

read more, refer to the article: ref and out keywords


15. What is Boxing and Unboxing in C#?
Boxing and unboxing is an important concept in C#. C# Type System contains three data types: Value
Types (int, char, etc), Reference Types (object), and Pointer Types. Basically, it converts a Value Type to
a Reference Type, and vice versa. Boxing and Unboxing enable a unified view of the type system in
which a value of any type can be treated as an object.
Boxing In C#
 The process of Converting a Value Type (char, int, etc.) to a Reference Type(object) is called
Boxing.
 Boxing is an implicit conversion process in which object type (supertype) is used.
 The Value type is always stored in Stack. The Referenced Type is stored in Heap.
Unboxing In C#
 The process of converting the reference type into the value type is known as Unboxing.
 It is an explicit conversion process.
To read more, refer to the article: C# – Boxing and Unboxing

16. What are Properties in C#?


Properties are the special type of class members that provides a flexible mechanism to read, write, or
compute the value of a private field. Properties can be used as if they are public data members, but they
are actually special methods called accessors. This enables data to be accessed easily and helps to
promote the flexibility and safety of methods. Encapsulation and hiding of information can also be
achieved using properties. It uses pre-defined methods which are “get” and “set” methods which help to
access and modify the properties.
Accessors: The block of “set” and “get” is known as “Accessors”. It is very essential to restrict the
accessibility of the property. There are two types of accessors i.e. get accessors and set accessors.
There are different types of properties based on the “get” and set accessors:
 Read and Write Properties: When property contains both get and set methods.
 Read-Only Properties: When property contains only the get method.
 Write Only Properties: When property contains only set method.
 Auto Implemented Properties: When there is no additional logic in the property accessors,
and it introduces in C# 3.0. To read more, refer to the article: Properties in C#

17. What are partial classes in C#?

A partial class is a special feature of C#. It provides a special ability to implement the
functionality of a single class into multiple files and all these files are combined into a single
class file when the application is compiled. A partial class is created by using a partial keyword.
This keyword is also useful to split the functionality of methods, interfaces, or structure into
multiple files.
public partial Class_name
{
// Code
}
To read more, refer to the article: Partial classes in C#
18. What is the difference between late binding and early binding in C#?

When an object is assigned to an object variable of the specific type, then the C# compiler
performs the binding with the help of .NET Framework. C# performs two different types of
bindings which are:
 Early Binding
 Late Binding or Dynamic Binding
It recognizes and checks the methods, or properties during compile time. In this binding, the
compiler already knows about what kind of object it is and what are the methods or properties
it holds, here the objects are static objects. The performance of early binding is fast and it is
easy to code. It decreases the number of run-time errors.
In late binding, the compiler does not know about what kind of object it is and what are the
methods or properties it holds, here the objects are dynamic objects. The type of the object is
decided on the basis of the data it holds on the right-hand side during run-time. Basically, late
binding is achieved by using virtual methods. The performance of late binding is slower than
early binding because it requires lookups at run-time. To read more, refer to the article: Early
binding and Late Binding

19. What are the different ways in which a method can be Overloaded in C#?

Method Overloading is the common way of implementing polymorphism. It is the ability to


redefine a function in more than one form. A user can implement function overloading by
defining two or more functions in a class sharing the same name. C# can distinguish the
methods with different method signatures. i.e. the methods can have the same name but with
different parameters list (i.e. the number of the parameters, order of the parameters, and data
types of the parameters) within the same class.
 Overloaded methods are differentiated based on the number and type of the
parameters passed as arguments to the methods.
 You can not define more than one method with the same name, Order, and type of
the arguments. It would be a compiler error.
 The compiler does not consider the return type while differentiating the overloaded
method. But you cannot declare two methods with the same signature and different
return types. It will throw a compile-time error. If both methods have the same
parameter types, but different return types, then it is not possible. To read more,
refer to the article: Method Overloading in C#

20. What is Reflection in C#?


Reflection is the process of describing the metadata of types, methods, and fields in a code. The
namespace System. Reflection enables you to obtain data about the loaded assemblies, the elements
within them like classes, methods, and value types. To read more, refer to the article: Reflection in
C#

21. What is the difference between constant and read-only in C#?

In C#, a const keyword is used to declare constant fields and constant local. The value of the
constant field is the same throughout the program or in other words, once the constant field is
assigned the value of this field is not be changed. In C#, constant fields and locals are not
variables, a constant is a number, string, null reference, boolean values. readonly keyword is
used to declare a readonly variable. This readonly keyword shows that you can assign the
variable only when you declare a variable or in a constructor of the same class in which it is
declared.

To read more, refer to the article: constant and read-only in C#

22. Can multiple catch blocks be executed?


The main purpose of the catch block is to handle the exception raised in the try block. This
block is only going to execute when the exception is raised in the program. In C#, You can use
more than one catch block with the try block. Generally, multiple catch block is used to handle
different types of exceptions means each catch block is used to handle different type of
exception. If you use multiple catch blocks for the same type of exception, then it will give you a
compile-time error because C# does not allow you to use multiple catch block for the same type
of exception. A catch block is always preceded by the try block.
In general, the catch block is checked within the order in which they have occurred in the
program. If the given type of exception is matched with the first catch block, then the first catch
block executes and the remaining of the catch blocks are ignored. And if the starting catch block
is not suitable for the exception type, then the compiler searches for the next catch block. To
read more, refer to the article: Multiple catch block in C#

23. What is Jagged Arrays?


A jagged array is an array of arrays such that member arrays can be of different sizes. In other
words, the length of each array index can differ. The elements of Jagged Array are reference
types and initialized to null by default. Jagged Array can also be mixed with multidimensional
arrays. Here, the number of rows will be fixed at the declaration time, but you can vary the
number of columns. To read more, refer to the article: Jagged Array in C#

24. What is the System. String and [Link] classes?


C# StringBuilder is similar to Java StringBuilder.

A String object is immutable, i.e. a String cannot be changed once created. Every time when you
use any of the methods of the System. String class, then you create a new string object in
memory. For example, a string “GeeksForGeeks” occupies memory in the heap, now, changing
the initial string “GeeksForGeeks” to “GFG” will create a new string object on the memory heap
instead of modifying the initial string at the same memory location. In situations where you
need to perform repeated modifications to a string, we need the StringBuilder class.

To avoid string replacing, appending, removing, or inserting new strings in the initial string C#
introduce StringBuilder concept. StringBuilder is a dynamic object. It doesn’t create a new
object in the memory but dynamically expands the needed memory to accommodate the
modified or new string. To read more, refer to the article: [Link] and
[Link] in C#

25. What’s the difference between the [Link]() and [Link]() ?


The [Link]() technique makes a replica of the components into
another existing array. It makes copies the components of one cluster to
another existing array. The Clone() technique returns a new array object
containing every one of the components in the first array. The Clone() makes a
duplicate of an array as an object, consequently should be cast to the real
exhibit type before it tends to be utilized to do definitely. The clone is of a
similar type as the first Array.

26. What is the difference between to dispose and finalize methods in C#?

The primary difference between dispose() and finalize() is that the


 dispose() is part of the IDisposable interface and is called explicitly by the user. Dispose()
is called when we want for an object to release any unmanaged resources with them
 finalize() is a destructor method called by the garbage collector when the object is
destroyed.
Dispose gives you more control over when resources are released, whereas Finalize relies on
the garbage collector.

27. What are delegates in C#?

A delegate is an object which refers to a method, or you can say it is a reference type variable
that can hold a reference to the methods.

Delegates in C# are similar to the function pointer in C/C++. It provides a way that tells which
method is to be called when an event is triggered.

For example, if you click a button on a form (Windows Form application), the program would
call a specific method. In simple words, it is a type that represents references to methods with a
particular parameter list and return type and then calls the method in a program for execution
when it is needed. To read more, refer to the article: Delegates in C#
28. What are sealed classes in C#?
Sealed classes are used to restrict the users from inheriting the class. A class
can be sealed by using the sealed keyword. The keyword tells the compiler that
the class is sealed, and therefore, cannot be extended. No class can be derived
from a sealed class.
The following is the syntax of a sealed class :
sealed class class_name
{
// data members
// methods
.
.
.

}
A method can also be sealed, and in that case, the method cannot be
overridden. However, a method can be sealed in the classes in which they have
been inherited. If you want to declare a method as sealed, then it has to be
declared as virtual in its base class. To read more, refer to the article: Sealed
Classes in C#

29. What is the Constructor Chaining in C#?

We can call an overloaded constructor from another constructor using this keyword but the
constructor must belong to the same class because this keyword is pointing to the members of
the same class in which this is used. This type of calling the overloaded constructor is also
termed as Constructor Chaining. To read more, refer to the article: Constructor Chaining

30. What is a multicasting delegate in C#?


Multicasting of delegate is an extension of the normal delegate(sometimes termed as Single
Cast Delegate). It helps the user to point more than one method in a single call.
31. What are Generics in C#?
Generic is a class that allows the user to define classes and methods with the placeholder.
Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is
to allow type (Integer, String, … etc, and user-defined types) to be a parameter to methods,
classes, and interfaces. A primary limitation of collections is the absence of effective type
checking. This means that you can put any object in a collection because all classes in the C#
programming language extend from the object base class. This compromises type safety and
contradicts the basic definition of C# as a type-safe language. In addition, using collections
involves a significant performance overhead in the form of implicit and explicit type casting that
is required to add or retrieve objects from a collection. To read more, refer to the
article: Generics in C#

32. Describe Accessibility Modifiers in C#?


Access Modifiers are keywords that define the accessibility of a member, class, or datatype in a
program. These are mainly used to restrict unwanted data manipulation by external programs
or classes. There are 4 access modifiers (public, protected, internal, private) which defines the 6
accessibility levels as follows:
 public
 private
 private protected
 protected
 internal
 protected internal

33. What is a Virtual Method in C#?

In C# virtual method is a strategy that can be reclassified in derived classes. We can implement
the virtual method in the base class and derived class. It is utilized when a method’s
fundamental work is similar but in some cases derived class needed additional functionalities. A
virtual method is declared in the parent class that can be overriden in the child class. We make
a virtual method in the base class by using the virtual keyword and that method is overriden in
the derived class using the Override keyword. It is not necessary for every derived class to
inherit a virtual method, but a virtual method must be created in the base class. Hence the
virtual method is also known as Polymorphism. To read more, refer to the article: Virtual
Method in C#

34. What is Multithreading with .NET?

Multi-threading is a process that contains multiple threads within a single process. Here each
thread performs different activities.

For example, we have a class and this call contains two different methods, now using
multithreading each method is executed by a separate thread. So the major advantage of
multithreading is it works simultaneously, which means multiple tasks execute at the same
time. And also maximizing the utilization of the CPU because multithreading works on time-
sharing concept mean each thread takes its own time for execution and does not affect the
execution of another thread, this time interval is given by the operating system. To read more,
refer to the article: Multithreading in C#
35. What is a Hash table class in C#?
The Hashtable class represents a collection of key/value pairs that are organized based on the
hash code of the key. This class comes under the System. Collections namespace. The Hashtable
class provides various types of methods that are used to perform different types of operations
on the hashtables. In Hashtable, keys are used to access the elements present in the collection.
For very large Hashtable objects, you can increase the maximum capacity to 2 billion elements
on a 64-bit system.

36. What is LINQ in C#?

LINQ is known as Language Integrated Query and it is introduced in .NET 3.5 and Visual Studio
2008. The beauty of LINQ is it provides the ability to .NET languages(like C#, [Link], etc.) to
generate queries to retrieve data from the data source. For example, a program may get
information from the student records or accessing employee records, etc. In, past years, such
type of data is stored in a separate database from the application, and you need to learn
different types of query language to access such type of data like SQL, XML, etc. And also you
cannot create a query using C# language or any other .NET language.
To overcome such types of problems Microsoft developed LINQ. It attaches one, more power to
the C# or .NET languages to generate a query for any LINQ compatible data source. And the
best part is the syntax used to create a query is the same no matter which type of data source is
used means the syntax of creating query data in a relational database is the same as that used
to create query data stored in an array there is no need to use SQL or any
other [Link] language mechanism. You can also use LINQ with SQL, with XML files, with
[Link], with web services, and with any other database. To read more, refer to the
article: LINQ in C#

37. Why a private virtual method cannot be overridden in C#?

Because private virtual methods are not accessible outside the class.

38. What is File Handling in C#?

Generally, the file is used to store the data. The term File Handling refers to the various
operations like creating the file, reading from the file, writing to the file, appending the file, etc.
There are two basic operations that are mostly used in file handling is reading and writing of the
file. The file becomes stream when we open the file for writing and reading. A stream is a
sequence of bytes that is used for communication. Two streams can be formed from the file
one is the input stream which is used to read the file and another is the output stream is used
to write in the file. In C#, the [Link] namespace contains classes that handle input and
output streams and provide information about file and directory structure.

39. List down the commonly used types of exceptions?


An exception is an error that happens at runtime. Using C#’s exception-handling subsystem, we
can, during a structured and controlled manner, handle runtime errors. The primary advantage
of exception handling is that it automates much of the error handling code. An Exception
handling is additionally important because C# defines standard exceptions for common
program errors, like divide-by-zero or index-out-of-range.
C# Exception with their meaning:
 ArrayTypeMismatchException: This exception comes when the Type of value being
stored is incompatible with the type of the array.
 DivideByZeroException: It comes when the user tries to division an integer value by
zero.
 IndexOutOfRangeException: When an array index is out-of-bounds, it exception
occurred.
 InvalidCastException: A runtime cast is invalid.
 OutOfMemoryException: Insufficient free memory exists to continue program
execution.
 OverflowException: An arithmetic overflow occurred.
 NullReferenceException: An attempt was made to operate on a null reference—that
is, a reference that does not refer to an object.

40. What is the difference between “is” and “as” operators in C#?

C# includes three keywords that support runtime type identification: is, as, and typeof.

is operator: We can determine if an object is of a particular type by using the is operator. Its
general form is shown here:
expr is type
Here, expr is an expression that describes an object whose type is being tested against type. If
the type of expr is that the same as, or compatible with, type, then the result of this operation
is true. Otherwise, it is false. Thus, if the result is true, expr is a form of type. Because it applies
to is, one type is compatible with another if both are the equivalent of type, or if a reference,
boxing, or unboxing conversion exists.

As operator: Sometimes if we want to try a conversion at runtime, but not throw an exception
if the conversion fails (which is the case when a cast is used). To do this, use the as operator,
which has this general form:

expr as type
Here, expr is the expression being converted to type. If the conversion succeeds, then a
reference to type is returned. Else, a null reference is returned. The as the operator can be used
to perform only reference, boxing, unboxing, or identity conversions. The as operator offers a
streamlined alternative to is in some cases.
41. What is Singleton design pattern in C#?

Singleton design pattern in C# is a common design pattern. In this pattern, a class has just one
instance in the program that gives global access to it. Or we can say that a singleton is a class
that permits only one instance of itself to be made and usually gives simple access to that
instance.
There are different approaches to carry out a singleton design in C#. Coming up next are the
regular attributes of a singleton design.
 Private and parameterizes single constructor
 Sealed class.
 Static variable to hold a reference to the single made example
 A public and static method of getting the reference to the made example.

42. How to implement a singleton design pattern in C#?

We can implement a singleton design pattern in C# using:


 No Thread Safe Singleton.
 Thread-Safety Singleton.
 Thread-Safety Singleton using Double-Check Locking.
 Thread-safe without a lock.
 Using .NET 4’s Lazy<T> type.

43. What is tuple in C#?

The word Tuple means “a data structure which consists of the multiple parts”.

So tuple is a data structure that gives you the easiest way to represent a data set that has
multiple values that may/may not be related to each other.

It was introduced in .NET Framework 4.0.


 In tuple, you can add elements from 1 to 8. If you try to add elements greater than
eight, then the compiler will throw an error.

Tuples are generally used when you want to create a data structure that contains objects with
their properties and you don’t want to create a separate type for that. To read more. please
refer to the article: Tuples in C#
44. What are Events?

An event is a notification that some action has occurred. Delegates and events are related
because an event is built upon a delegate. Both expand the set of programming tasks to which
C# can be applied. It is an important C# feature is built upon the foundation of delegates:
the event. An event is, essentially, an automatic notification that some action has occurred.
Events work like this:
An object that has an interest in an event registers an event handler for that event. When the
event occurs, all registered handlers are called. Event handlers are represented by delegates.
Events are members of a class and are declared using the event keyword. Its most commonly
used form is shown here:
event event-delegate event-name;
Here, event-delegate is the name of the delegate used to support the event, and event-name is
the name of the specific event object being declared.

46. What is the difference between Array and ArrayList?


An array is a group of like-typed variables that are referred to by a common name. ArrayList
represents an ordered collection of an object that can be indexed individually. It is basically an
alternative to an array. Below are the major differences

To read more about this, please refer to C# – Array vs ArrayList

47. Write a Features of Generics in C#?


Generics is a technique that improves your programs in many ways such as:
 It helps you in code reuse, performance, and type safety.
 You can create your own generic classes, methods, interfaces, and delegates.
 You can create generic collection classes. The .NET Framework class library contains
many new generic collection classes in [Link] namespace.
 You can get information on the types used in generic data types at run-time.

48. Difference between SortedList and SortedDictionary in C#.

SortedList a collection of key/value pairs that are sorted according to keys. By default, this
collection sort the key/value pairs in ascending order. It is of both generic and non-generic
types of collection.
SortedDictionary a generic collection that is used to store the key/value pairs in the sorted form
and the sorting is done on the key.
Below are some differences between SortedList and SortedDictionary:

To read more about this, you can refer to Difference between SortedList and
SortedDictionary in C#

49. What are namespaces in C#?


It provides a way to keep one set of names(like class names) different from other sets of names.
The biggest advantage of using namespace is that the class names which are declared in one
namespace will not clash with the same class names declared in another namespace. It is also
referred as named group of classes having common features. To read more about this, please
refer to Namespaces in C#

50. Who can be the members of namespaces in C#?

The members of a namespace can be namespaces, interfaces, structures, and delegates.

Q7. List down the access modifiers available in C#.

Ans- Following are the access modifiers available for general use:

 Public- When an attribute or method is defined as public it can be accessed from any
part of code.
 Private- A private attribute or method can be accessed from within the class itself.
 Protected- When a user defines a method or attribute as protected then it can be
accessed only within that class and the one inheriting the class.
 Internal- When an attribute or method is defined as internal then it will be accessed
from that class at the current assembly position.
 Protected Internal- When you define an attribute or method as protected internal, then
it’s access restricted to classes within the current project assembly or different types
defined by that class.

Q8. List down the different IDE’s Provided by Microsoft for C# Development.

Ans- Below listed are few IDE’s for C# development:

 Visual Studio Express (VCE)


 Visual Studio (VS)
 Visual Web Developer
 MonoDevelop
 browxy

Q9. Distinguish between Continue and Break Statement?

Ans- Using break statement you can ‘jump out’ of the loop whereas while making use of
continue statement you can jump over an iteration and continue the loop execution.

Example (Break Statement):

1using System;
2
3
4
5
6
7
8
9
1
0using [Link];
1using [Link];
1using [Link];
1
2namespace break_example{
1Class break_Stmnt{
3public static void main(String args[]){
1for(int i=0;i<=6;i++)
4{
1if(i==5)
5{
1break;
6}
[Link]("The number is +i");
7}
1}
8}
Output:

the number is 0;
the number is 1;
the number is 2;
the number is 3;
the number is 4;

Example (Continue Statement):

1using System;
2using [Link];
3using [Link];
4using [Link];
5
6namespace continue_example{
7Class continue_Stmnt{
8public static void main(String args[]){
9for(int i=0;i<=6;i++)
1{
0
1
1
1
2
1
3
1
4
1if(i==5)
5{
1continue;
6}
[Link]("The number is +i");
7}
1}
8}
Output:

the number is 0;
the number is 1;
the number is 2;
the number is 3;
the number is 5;

Q10. What are the different approaches of passing parameters to a method?

Ans- There are three ways of passing parameters to a method:

Value Parameters- Under this method the actual value of an argument is copied to the formal
parameter of the function. In, this case the changes made into the formal parameter of the
function have no effect on the actual value of the argument.

Reference Parameters- This method copies the argument referring to the memory location into
the formal parameter. Meaning changes made to the parameter affect the argument.

Output Parameters- This method returns more than one value.

Let’s move ahead in C# Interview Questions and see the next category.

Intermediate level C# Interview Questions


Q11. Distinguish between finally and finalize blocks?
Ans- finally block is called after the execution of try and catch blocks. It is used for exception
handling whether or not the exception has been caught this block of code gets executed.
Generally, this block of code has a cleaner code.

The finalize method is called just before the garbage collection. Main priorities are to perform
clean up operation for unmanaged code, it is automatically invoked when an instance is not
subsequently called.

Q12. What is Managed or Unmanaged Code?

Ans- Managed code is one which is executed by CLR (Common Language Runtime) in simple
terms it means all the application code is dependent on the .NET platform, considered as
overseen in view of them. Unmanaged code is any code that is executed by runtime application
of some other structure different from .NET platform. The runtime of application will deal with
memory, security and other execution activities.

Q13. What is an Object?

Ans- Object is an instance of a class, It is used for accessing the methods of a class. “New”
keyword is used for the creation of an object, a class that creates an object in the memory
location contains the information about methods, variables, and behavior of that class.

To know more about Object in Java, Python, and C++ you can go through the following blog:

 Java Object
 Python Object
 C++ Object

Q14. What is a Class?

Ans- A class is a blueprint of an object. It defines different kinds of data and functionalities
objects will have. A class enables you to create your own custom types by clubbing together
variables of different types, methods, and events. In C# a class is defined by a class keyword.

To know more about Class in Java, Python, and C++ you can go through the following blog:

 Java Class
 Python Class
 C++ Class

Q15. Define an abstract class?

Ans- It is a type of class whose objects can’t be instantiated. It contains something like a single
approach or technique and indicated by the keyword ‘abstract’.
To know more about abstract class in Java you can go through the following blog:

 Java abstract class

Q16. Define sealed classes in C#?

Ans- You create sealed classes in situations when you want to restrict the class to be inherited.
For doing this sealed modifiers are used. If you forcefully specify a sealed class as a base class
then a compilation error occurs.

Q17. Define a Partial class?

Ans- A partial class is the only one that essentially splits the definition of a class into multiple
classes in either same source code files or multiple source code files. One can create a class
definition in multiple files but that is compiled as one class at run-time and when an instance of
this class is created, one can access all methods from every source file with the same object. It
is indicated by the keyword ‘partial’.

Q18. List down the fundamental OOP concepts?

Ans- There are four fundamental OOP (Object Oriented Programming) concept they are listed
as follows:

 Inheritance- Ever heard of this dialogue from relatives “you look exactly like your
father/mother” the reason behind this is called ‘inheritance’. From the Programming
aspect, It generally means “inheriting or transfer of characteristics from parent to child
class without any modification”. The new class is called the derived/child class and the
one from which it is derived is called a parent/base class.
 Polymorphism- You all must have used GPS for navigating the route, Isn’t it amazing
how many different routes you come across for the same destination depending on the
traffic, from a programming point of view this is called ‘polymorphism’. It is one such
OOP methodology where one task can be performed in several different ways. To put it
in simple words, it is a property of an object which allows it to take multiple forms.
 Encapsulation- In a raw form, encapsulation basically means binding up of data in a
single class.A class shouldn’t be directly accessed but be prefixed in an underscore.
 Abstraction- Suppose you booked a movie ticket from bookmyshow using net banking or
any other process. You don’t know the procedure of how the pin is generated or how
the verification is done. This is called ‘abstraction’ from the programming aspect, it
basically means you only show the implementation details of a particular process and
hide the details from the user. It is used to simplify complex problems by modeling
classes appropriate to the [Link] abstract class cannot be instantiated which
simply means you cannot create objects for this type of class. It can only be used for
inheriting the functionalities.
To know more about OOPs in Java, Python, and C++ you can go through the following blogs:

 Java OOPs
 Python OOPs
 C++ OOPs

Q19. Explain the process of inheriting a class into another class?

Ans- Colon is used as an inheritance operator in C#. Place the colon and the class name.

1public class Derivedclass: childclass


Q20. Define method overloading in C#?

Ans- Method overloading essentially is creating multiple methods with the same name and
unique signatures with the same class. When you compile, the compiler makes use of overload
resolution to determine the specific method which will be invoked.

Q21. List the differences between method overriding and method overloading?

Ans- Under Method overriding the definition of the derived class is changed which in turn
changes the method behavior. Method overloading is simply creating a method with the same
name under the same class under different signatures.

Q22. Explain StreamReader/StreamWriter class?

Ans- Streamreader and StreamWriter are classes of [Link]. Used when we want
to read or write charact90, Reader based data, respectively.

members of StreamReader are: close(), Read(), Readline().


members of Streamwriter are: close(), write(), writeline().

Example program:

1Class Testprogram
2{
3using(StreamReader sr = new StreamReader("C:[Link]")
4{
5// Any code to read//
6}
7using(StreamWriter sr = ndew StreamWriter("C:[Link]")
8{
9// Any code to write//
1}
0}
1
1
Q23. What is an Interface?

Ans- An Interface is basically a class with no implementation. It contains only the declaration of
properties, attributes, and events.

Q24. Distinguish between a class and struct?

Ans- Given below are the differences between a class and struct:

Class Struct
It supports inheritance It does not support inheritance
It is Pass by reference It is pass by value
Members are private by default Members are public by default
Considered good for larger complex
Considered good for small models
objects

Q25. List the difference between the Virtual method and the Abstract method?

Ans- A Virtual method must always have a default implementation. However, it can be
overridden in a derived class by the keyword override.

An Abstract method doesn’t have any implementation. It resides in the abstract class, and also
it is mandatory that the derived class must implement abstract class. Use of override keyword is
not necessary.

Q26. Illustrate Namespaces in C#?

Ans- Namespaces are used for organizing large code projects. “System” is one of the most
popular and widely used namespaces in C#. One can create their own namespace and use one
into another called nesting.

Q27. Define using statement in C#?

Ans- “Using” keyword simply denotes that the particular namespace is being used by the
program. For ex- using System, Here System is a namespace. The class console is defined under
system, so we can use the [Link](…) or Readline in our program.

Q28. Define an Escape Sequence, Name few strings in Escape Sequence?


Ans- An Escape Sequence is denoted by a backslash (). The backslash merely indicates that the
character it is following should be interpreted literally or is a special character. An escape
sequence is a single character.

Few escape sequences are as follows:

n – newline character

b – backspace

– backlash

‘ – Single quote

” – Double quote

Q29. Define Boxing and Unboxing in C#?

Ans- Converting a value type to the reference type is called boxing.

Example:

1int value = 10
2//-------Boxing--------//
3object boxedvalue = value1;
Explicit conversion of the same reference type i.e. converting it back to the
value type is called Unboxing.

Example:

1//----------------Unboxing-------// int UnBoxing = int(boxedvalue);


To know more about Boxing and Unboxing in Java you can go refer this
article- Boxing in Java.

Q30. Define an array?

Ans- An array is used to store multiple variables of the same type. Collection of variables stored
in a contiguous memory location.

Example:
double numbers = new double[10];
int[] Score = new int[4] {25,24,23,22,21,20}
Above given example above is of a Single Dimensional array. It is a linear array where values are
stored in a single row. A multidimensional array is the one having more than one dimension. A
good example would be of a rectangle.

Example:

int[,] numbers = new int[4,3]{ {1,2} {2,3} {3,4} {4,5} };

To know more about arrays in Java, Python , and C++ you can go through
the following blogs:

 Python array
 Java array
 C++ array

Q31. Define a Jagged Array in C#?

Ans- A Jagged array is referred to as an “array of arrays”. It is an array


whose elements are arrays, the element of the same can be of different
dimensions and sizes. The length of each array index can differ.

Example:

int[][] jagArray = new int[5][];

Q32. Distinguish between Array and Arraylist in C#?

Ans-

Array ArrayList
Array uses the vector array for ArrayList uses the LinkedList to store
storing the elements the elements
Size of the Array must be defined There’s no need for specifying
until redim used(vb) storage size.
An array is a specific data type ArrayList can store everything as an
storage object
Typecasting is not necessary Typecasting is necessary
There is no RunTime exception There is a RunTime error exception
Elements can’t be inserted or deleted Elements can be inserted or deleted
in between in between
Q33. Define Collections?

Ans- A collection essentially works like a container for instances of other classes. Every class
implements Collection Interface.
To know more about collections in Java, check out the following blog:

 Java Collections

Q34. Write a short note on Interface?

Ans- An Interface is a class with no implementation. It consists of a


declaration of methods, Parameters, and values.

To know more about Interface in Java, check out the following blog:

 Java Interface

Moving on in C# Interview Question let’s see the next category.

Advanced Level
Q35. Illustrate Serialization?

Ans- A process that involves converting some code into its binary format is known as a
serialization in C#. In doing so it gives the flexibility where code can be stored easily and or
written to a disk or some other storage device. Serialization is used when there is a strict need
for not losing the original code.

Serialization in C# is of three types:

Binary Serialization- It is fast and demands less space, converts any code into its binary format.
Serialize and restore public and non-public properties.

SOAP- Generates a complete SOAP compliant envelope used by any system by its ability to
understand SOAP. Classes under this type of Serialization reside
in [Link].

XML Serialization- It serializes all the public properties to XML document. Readability being one
factor, an XML document can also be manipulated in various ways. Classes under this type
reside in [Link].

To know more about Serialization in Java, check out the following blog:

 Java Serialization

Q36. Define Parsing? Explain how to Parse a DateTime String?

Ans- Parsing is a method of converting a string into another data type.


Example:

1string text = "200";


2int num = [Link](text);
In the above-given example, 200 is an integer. So, the Parse method converts the string 200
into its own base type, i.e. int.

To parse a DateTime String let’s see a small example.

Example:

string dateTime = "Aug 26,2019"; Datetime parsedvalue =


[Link](dateTime);

Q37. Define Delegate?

Ans- Delegate is a variable that holds the reference to a method. It is a function pointer of the
reference type. All Delegates are derived from the [Link] namespace. Both Delegate
and the method that it refers to can have the same signature. Let’s see a small example.

Example:

1
2
3
4public Delegate int myDel(int number); //declaring a delegate
5public class Program
6{
7public int SubstractNumbers(int a) //Class Program has the method same si
8called
9{
1int difference = a - 10;
0return difference;
1}
1public void start()
1{
2myDel DelegateExample = SubstractNumbers;
1}
3}
Q38. Distinguish between [Link] and [Link] classes?

Ans – [Link] is immutable. Whenever you modify the value of a string variable then a
new memory is allocated to the new value and previous memory allocation is released.
[Link] is mutable i.e. supports the fact that a variety of operations can be
performed without allocating a seperate memory location for the already modified string.

Q39. Illustrate the differences between the [Link]() and [Link]()?

Ans – Using the Clone() method, a new array object is created containing all elements of the
original array. Using the CopyTo() method all the elements of the existing array gets copied into
another existing array. Both use a shallow copy method.

Q40. Write the Syntax for catching an exception in C#?

Ans – To catch an Exception we make use of try-catch blocks. The catch block has a parameter
of the [Link] type.

Example:

1try
2{
3GetAllData();
4}
5catch(Exception ex){
6}
Q41. Explain about generics in C#.NET?

Ans- Generics are used to make reusable code classes which decrease the code redundancy,

 Increase type safety, performance, and optimization


 Using Generics one can do a variety of things like create collections
 To create Generic collection, [Link]
 The generic namespace should be used inspite of classes such as ArrayList in the System
 Generics instigates the usage of a parameterized type

Q43. Define C# I/O classes? List the commonly used classes?

Ans- C# consists of [Link] namespace which has classes that compute and perform various
operations on files like creating, deleting, opening
and closing etc.

Few commonly used I/O classes are listed below:

File- Helps in manipulating file.


StreamWriter- Generally used for writting characters to a stream.
StreamReader- Generally used for reading characters to a stream.
StringWriter- Used for writing a string buffer.
Stringreader- Used for reading a string buffer.
Q44. Define thread? Explain about Multithreading?

Ans- Thread is a set of instructions that when executed enables the program to perform
concurrent processing. Concurrent processing helps in doing more than one process at a time.
By default, C# consists of only thread. Other threads can be created to execute the code in
parallel with original thread.

Thread follows a life cycle where it starts whenever a thread is created and gets terminated
immediately after the execution. The namespace it follows is [Link] which has to be
included to create threads and use its members.

Threads are created by extending the thread class. Start() method marks the beginning of the
thread execution.

1//callThread is our target method//


2ThreadStart methodThread = new ThreadStart(CallThread);
3Thread childThread = new Thread(methodThread);
[Link]();
C# can also execute more than proceeses/task at a time which is done by handling different
processes at different time labeled as “multithreading”. Several operations of the same are
listed below:

 Start
 Sleep
 Abort
 Suspend
 Resume
 Join

To know more about Threads in Java, you can go through the following blog:

 Java Thread
 Multithreading in Python

Let’s move on in C# Interview Questions and see the next question.

Q45. What are Events?

Ans- Events in C# follow a concept where it consists of a Publisher,


Subscriber, Notification and a handler. You can think of an event as nothing
but an encapsulated delegate.

Example:

1public Delegate void TestEvent();


2public TestEvent TestEvent1;
Q46. Explain Synchronous and Asynchronous Operations?

Ans- Synchronization is a way of creating a thread-safe code where only a


single thread will access the code in a given time. A synchronous call waits
for completion of method and then continous the program flow. Synchronous
programming adversely affects the UI operations that normally happens
when user tries to perform time-consuming operations since only one thread
is used.

In Asynchronous operation, the method call immediately returns allowing the


program to perform other operations while the method called completes its
share of work in certain circumstances.

Q47. Explain Async and Await?

Ans- Async and Await keywords are mostly used for creating asynchronous
methods in C#. Usage of the same is shown through an example:

1
2public async Task>CalculateCount()
3{
4await [Link](2000);
5return 1;
6}
7public async task mytestmethod()
8{
9Task> count = CalculateCount();
1int result = await count;
0}
In the above-given code async keyword is used for method declaration. The
Count is of a task type int which calls the method CalculateCount().
CalculateCount() starts execution and calculates something.

Q48. Explain Deadlock?

Ans- A deadlock is a situation that arises when a process isn’t able to


complete it’s execution because two or more than two processes are waiting
for each other to finish. This usually occurs in multi-threading. In this, a
shared resource is being held up by a process and another process is waiting
for the first process to get over or release it, and the thread holding the
locked item is waiting for another process to complete.

Q49. Illustrate Race Condition?


Ans- A Race Condition occurs in a situation when two threads access the same resource and try
to change it at the same time. The thread which accesses the resource first cannot be
predicted. Let me take a small example where two threads X1 and X2 are trying to access the
same shared resource called T. And if both threads try to write the value to T, then the last
value written to T will be saved.

Q50. What is Thread Pooling?

Ans- A Thread pool is a collection of threads that perform tasks without disturbing the primary
thread. Once the task is completed by a thread it returns to the primary thread.

This brings us to the end of this article on C# Interview Questions. I hope it helped in adding up
to your knowledge. Wishing you all the best for your interview. Happy learning.

In case you are looking for the most common Technical Interview Questions, read along:

 OOPs Interview Questions


 MVC Interview Questions
 SQL Interview Questions
 Java Interview Questions
 Python Interview Questions

1. What is C#?
C# is an object-oriented, type-safe, and managed language that is compiled by .Net framework
to generate Microsoft Intermediate Language.

2. Explain types of comment in C# with examples


Single line

Example:

//This is a single line comment


ii. Multiple line (/* */)

Example:
/*This is a multiple line comment
We are in line 2
Last line of comment*/
iii. XML Comments (///).

Eg:
/// summary;
/// Set error message for multilingual language.
/// summary
3. Can multiple catch blocks be executed?
No, Multiple catch blocks of similar type can’t be executed. Once the proper catch code
executed, the control is transferred to the finally block, and then the code that follows the
finally block gets executed.

4. What is the difference between public, static, and void?


 Public declared variables or methods are accessible anywhere in the application.

 Static declared variables or methods are globally accessible without creating an instance of
the class. Static member are by default not globally accessible it depends upon the type of
access modified used. The compiler stores the address of the method as the entry point and
uses this information to begin execution before any objects are created.

 Void is a type modifier that states that the method or variable does not return any value.

5. What is an object?
An object is an instance of a class through which we access the methods of that class. “New”
keyword is used to create an object. A class that creates an object in memory will contain the
information about the methods, variables, and behavior of that class.

6. Define Constructors
A constructor is a member function in a class that has the same name as its class. The
constructor is automatically invoked whenever an object class is created. It constructs the
values of data members while initializing the class.

7. What is Jagged Arrays?


The Array which has elements of type array is called jagged Array. The elements can be of
different dimensions and sizes. We can also call jagged Array as an Array of arrays.

8. What is the difference between ref & out parameters?


An argument passed as ref must be initialized before passing to the method whereas out
parameter needs not to be initialized before passing to a method.

9. What is the use of ‘using’ statement in C#?


The ‘using’ block is used to obtain a resource and process it and then automatically dispose of
when the execution of the block completed.
10. What is serialization?
When we want to transport an object through a network, then we have to convert the object
into a stream of bytes. The process of converting an object into a stream of bytes is called
Serialization. For an object to be serializable, it should implement ISerialize Interface. De-
serialization is the reverse process of creating an object from a stream of bytes.

11. Can we use “this” command within a static method?


We can’t use ‘This’ in a static method because we can only use static variables/methods in a
static method.

12. What is the difference between constants and read-only?


Constant variables are declared and initialized at compile time. The value can’t be changed
afterward. Read-only is used only when we want to assign the value at run time.

C# Advanced Interview Questions for 3/5/10 Years


Experience
13. What is an interface class? Give one example of it
An Interface is an abstract class which has only public abstract methods, and the methods only
have the declaration and not the definition. These abstract methods must be implemented in
the inherited classes.

using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace DemoApplication
{
interface Guru99Interface
{
void SetTutorial(int pID, string pName);
String GetTutorial();
}

class Guru99Tutorial : Guru99Interface


{
protected int TutorialID;
protected string TutorialName;

public void SetTutorial(int pID, string pName)


{
TutorialID = pID;
TutorialName = pName;
}

public String GetTutorial()


{
return TutorialName;
}

static void Main(string[] args)


{
Guru99Tutorial pTutor = new Guru99Tutorial();

[Link](1,".Net by Guru99");

[Link]([Link]());

[Link]();
}
}
}

14. What are value types and reference types?


A value type holds a data value within its own memory space. Example

int a = 30;
Reference type stores the address of the Object where the value is being stored. It is a pointer
to another memory location.

string b = "Hello Guru99!!";

15. What are Custom Control and User Control?


Custom Controls are controls generated as compiled code (Dlls), those are easier to
use and can be added to toolbox. Developers can drag and drop controls to their
web forms. Attributes can, at design time. We can easily add custom controls to
Multiple Applications (If Shared Dlls). So, If they are private, then we can copy to dll
to bin directory of web application and then add reference and can use them.

User Controls are very much similar to ASP include files, and are easy to create.
User controls can’t be placed in the toolbox and dragged – dropped from it. They
have their design and code-behind. The file extension for user controls is ascx.

16. What are sealed classes in C#?


We create sealed classes when we want to restrict the class to be inherited. Sealed modifier
used to prevent derivation from a class. If we forcefully specify a sealed class as base class, then
a compile-time error occurs.

17. What is method overloading?


Method overloading is creating multiple methods with the same name with unique signatures
in the same class. When we compile, the compiler uses overload resolution to determine the
specific method to be invoke.

18. What is the difference between Array and Arraylist?


An array is a collection of elements of the same type, stored in contiguous memory locations.
Arrays are strongly-typed, meaning that once you declare an array of a specific type, you cannot
store elements of a different type in it. Arrays have a fixed size, which means you cannot
change the size of an array once it is created.
using System;

class GFG
{
public static void Main(string[] args) {
int[] arr = new int[4];
arr[0] = 47;
arr[1] = 77;
arr[2] = 87;
arr[3] = 97;
for (int i = 0; i < [Link]; i++) {
[Link](arr[i]);
}
}
}

An ArrayList is a collection that can store elements of any type, including different types in the
same collection. ArrayLists are part of the [Link] namespace and are not strongly-
typed. They allow dynamic resizing, meaning the size of an ArrayList can grow or shrink as
needed.

using System;
using [Link];

class GFG
{
public static void Main(string[] args)
{
ArrayList al = new ArrayList();
[Link]("Ajay");
[Link]("Ankit");
[Link](10);
[Link](10.10);
foreach (var item in al) {
[Link](item);
}
}
}

19. Can a private virtual method can be overridden?


No, because they are not accessible outside the class.

20. Describe the accessibility modifier “protected internal”.


Protected Internal variables/methods are accessible within the same assembly and also from
the classes that are derived from this parent class.

21. What are the differences between [Link] and [Link] classes?
[Link] is immutable. When we modify the value of a string variable, then a new memory
is allocated to the new value and the previous memory allocation released.
[Link] was designed to have a concept of a mutable string where a variety of
operations can be performed without allocation separate memory location for the modified
string.

22. What’s the difference between the [Link]() and [Link]() ?


Using Clone() method, we creates a new array object containing all the elements in the original
Array and using CopyTo() method. All the elements of existing array copies into another existing
array. Both methods perform a shallow copy.

23. How can we sort the elements of the Array in descending order?
Using Sort() methods followed by Reverse() method.

24. Write down the C# syntax to catch an exception


To catch an exception, we use try-catch blocks. Catch block can have a parameter
of [Link] type.

Eg:
try {
GetAllData();
}
catch (Exception ex) {
}
In the above example, we can omit the parameter from catch statement.

25. What’s the difference between an interface and abstract


class?
Interfaces have all the methods having only declaration but no definition. In an
abstract class, we can have some concrete methods. In an interface class, all the
methods are public. An abstract class may have private methods.

27. What are circular references?


Circular reference is situation in which two or more resources are interdependent
on each other causes the lock condition and make the resources unusable.

28. What are generics in C#.NET?


Generics are used to make reusable code classes to decrease the code redundancy,
increase type safety, and performance. Using generics, we can create collection
classes. To create generic collection, [Link] namespace
should be used instead of classes such as ArrayList in the [Link]
namespace. Generics promotes the usage of parameterized types.

29. What is an object pool in .NET?


An object pool is a container having objects ready to be used. It tracks the object
that is currently in use, total number of objects in the pool. This reduces the
overhead of creating and re-creating objects.

30. List down the commonly used types of exceptions in .net


ArgumentException, ArgumentNullException, ArgumentOutOfRangeException,
ArithmeticException, DivideByZeroException ,OverflowException,
IndexOutOfRangeException, InvalidCastException, InvalidOperationException,
IOEndOfStreamException , NullReferenceException, OutOfMemoryException,
StackOverflowException etc.

31. What are Custom Exceptions?


Sometimes there are some errors that need to be handled as per user
requirements. Custom exceptions are used for them and are used defined
exceptions.

32. What are delegates?


Delegates are same are function pointers in C++, but the only difference is that they
are type safe, unlike function pointers. Delegates are required because they can be
used to write much more generic type-safe functions.

33. How do you inherit a class into other class in C#?


Colon is used as inheritance operator in C#. Just place a colon and then the class
name.

public class DerivedClass : BaseClass

34. What is the base class in .net from which all the classes are
derived from?
[Link]
35. What is the difference between method overriding and
method overloading?
In method overriding, we change the method definition in the derived class that
changes the method behavior. Method overloading is creating a method with the
same name within the same class having different signatures.

36. What are the different ways a method can be overloaded?


Methods can be overloaded using different data types for a parameter, different
order of parameters, and different number of parameters.

37. Why can’t you specify the accessibility modifier for methods
inside the interface?
In an interface, we have virtual methods that do not have method definition. All the
methods are there to be overridden in the derived class. That’s why they all are
public.

38. How can we set the class to be inherited, but prevent the method from being over-ridden?
Declare the class as public and make the method sealed to prevent it from being overridden.

39. What happens if the inherited interfaces have conflicting


method names?
Implement is up to you as the method is inside your own class. There might be a
problem when the methods from different interfaces expect different data, but as
far as compiler cares you’re okay.

40. What is the difference between a Struct and a Class?


Structs are value-type variables, and classes are reference types. Structs stored on
the Stack causes additional overhead but faster retrieval. Structs cannot be
inherited.

41. How to use nullable types in .Net?


Value types can take either their normal values or a null value. Such types are called nullable
types.

Int? someID = null;


If([Link])
{
}
42. How we can create an array with non-default values?
We can create an array with non-default values using [Link].

43. What is difference between “is” and “as” operators in c#?


“is” operator is used to check the compatibility of an object with a given type, and it returns the
result as Boolean.

“as” operator is used for casting of an object to a type or a class.

44. What’s a multicast delegate?


A delegate having multiple handlers assigned to it is called multicast delegate. Each handler is
assigned to a method.

45. What are indexers in C# .NET?


Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed in the
same way as an array.
Eg:
public int this[int index] // Indexer declaration
46. What is difference between the “throw” and “throw ex” in .NET?
“Throw” statement preserves original error stack whereas “throw ex” have the stack trace from
their throw point. It is always advised to use “throw” because it provides more accurate error
information.

47. What are C# attributes and its significance?


C# provides developers a way to define declarative tags on certain entities, eg.
Class, method, etc. are called attributes. The attribute’s information can be
retrieved at runtime using Reflection.

48. How to implement a singleton design pattern in C#?


In a singleton pattern, a class can only have one instance and provides an access
point to it globally.

Eg:
Public sealed class Singleton
{
Private static readonly Singleton _instance = new Singleton();
}
49. What is the difference between directcast and ctype?
DirectCast is used to convert the type of object that requires the run-time type to
be the same as the specified type in DirectCast.

Ctype is used for conversion where the conversion is defined between the
expression and the type.

50. Is C# code is managed or unmanaged code?


C# is managed code because Common language runtime can compile C# code to
Intermediate language.

51. What is Console application?


A console application is an application that can be run in the command prompt in
Windows. For any beginner on .Net, building a console application is ideally the
first step, to begin with.
52. Give an example of removing an element from the queue
The dequeue method is used to remove an element from the queue.
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];

namespace DemoApplication
{
class Program
{
static void Main(string[] args)
{
Queue qt = new Queue();
[Link](1);
[Link](2);
[Link](3);

foreach (Object obj in qt)


{
[Link](obj);
}
[Link](); [Link]();
[Link]("The number of elements in the Queue " + [Link]);
[Link]("Does the Queue contain " + [Link](3));
[Link]();
}
}
}

2. What is Common Language Runtime (CLR)?

CLR handles program execution for various languages including C#. The
architecture of CLR handles memory management, garbage collection,
security handling, and looks like:
Architecture of CLR

3. What is garbage collection in C#?

Garbage collection is the process of freeing up memory that is captured by


unwanted objects. When you create a class object, automatically some
memory space is allocated to the object in the heap memory. Now, after
you perform all the actions on the object, the memory space occupied by
the object becomes waste. It is necessary to free up memory. Garbage
collection happens in three cases:

 If the occupied memory by the objects exceeds the pre-set threshold


value.
 If the garbage collection method is called
 If your system has low physical memory
4. What are the types of classes in C#?

Class is an entity that encapsulates all the properties of its objects and
instances as a single unit. C# has four types of such classes:

 Static class: Static class, defined by the keyword ‘static’ does not
allow inheritance. Therefore, you cannot create an object for a static
class.

Sample code:

static class classname


{
//static data members
//static methods
}

 Partial class: Partial class, defined by the keyword ‘partial’ allows its
members to partially divide or share source (.cs) files.
 Abstract class: Abstract classes are classes that cannot be
instantiated where you cannot create objects. Abstract classes work
on the OOPS concept of abstraction. Abstraction helps to extract
essential details and hide the unessential ones.
 Sealed class: Sealed classes are classes that cannot be inherited.
Use the keyword sealed to restrict access to users to inherit that
class.

sealed class InterviewBit


{
// data members
// methods
.
.
.
}

5. What is a managed and unmanaged code?

Managed code lets you run the code on a managed CLR runtime
environment in the .NET framework.
Managed code runs on the managed runtime environment than the
operating system itself.
Benefits: Provides various services like a garbage collector, exception
handling, etc.
Unmanaged code is when the code doesn’t run on CLR, it is an
unmanaged code that works outside the .NET framework.
They don’t provide services of the high-level languages and therefore, run
without them. Such an example is C++.

6. What is the difference between an abstract class and an interface?

Let’s dig into the differences between an abstract class and an interface:

 Abstract classes are classes that cannot be instantiated ie. that cannot create an object.
The interface is like an abstract class because all the methods inside the interface are
abstract methods.
 Surprisingly, abstract classes can have both abstract and non-abstract methods but all
the methods of an interface are abstract methods.
 Since abstract classes can have both abstract and non-abstract methods, we need to use
the Abstract keyword to declare abstract methods. But in the interface, there is no such
need.

An abstract class has constructors while an interface encompasses none.

Ex.

Abstract class:

public abstract class Shape{


public abstract void draw();
}

Interface:

public interface Paintable{


void paint();
}

7. What are the differences between ref and out keywords?

C# ref keywords pass arguments by reference and not value. To use the
‘ref’ keyword, you need to explicitly mention ‘ref’.

void Method(ref int refArgument)


{
refArgument = refArgument + 10;
}
int number = 1;
Method(ref number);
[Link](number);
// Output: 11
C# out keywords pass arguments within methods and functions.
‘out’ keyword is used to pass arguments in a method as a reference to
return multiple values. Although it is the same as the ref keyword, the ref
keyword needs to be initialised before it is passed. Here, The out and ref
keywords are useful when we want to return a value in the same variables
that are passed as an argument.

public static string GetNextFeature(ref int id)


{
string returnText = "Next-" + [Link]();
id += 1;
return returnText;
}
public static string GetNextFeature(out int id)
{
id = 1;
string returnText = "Next-" + [Link]();
return returnText;
}

8. What are extension methods in C#?

Extension methods help to add new methods to the existing ones. The
methods that are added are static. At times, when you want to add
methods to an existing class but don’t perceive the right to modify that
class or don’t hold the rights, you can create a new static class containing
the new methods. Once the extended methods are declared, bind this class
with the existing one and see the methods will be added to the existing
one.

// C# program to illustrate the concept


// of the extension methods
using System;

namespace ExtensionMethod {
static class NewMethodClass {

// Method 4
public static void M4(this Scaler s)
{
[Link]("Method Name: M4");
}

// Method 5
public static void M5(this Scaler s, string str)
{
[Link](str);
}
}
// Now we create a new class in which
// Scaler class access all the five methods
public class IB {

// Main Method
public static void Main(string[] args)
{
Scaler s = new Scaler();
s.M1();
s.M2();
s.M3();
s.M4();
s.M5("Method Name: M5");
}
}
}

Output:

Method Name: M1

Method Name: M2

Method Name: M3

Method Name: M4

Method Name: M5

9. What are Generics in C#?

In C# collections, defining any kind of object is termed okay which compromises C#’s basic rule
of type-safety.

Therefore, generics were included to type-safe the code by allowing re-use of the data
processing algorithms. Generics in C# mean not linked to any specific data type. Generics
reduce the load of using boxing, unboxing, and typecasting objects. Generics are always defined
inside angular brackets <>. To create a generic class, this syntax is used:

GenericList<float> list1 = new GenericList<float>();


GenericList<Features> list2 = new GenericList<Features>();
GenericList<Struct> list3 = new GenericList<Struct>();

Here, GenericList<float> is a generic class. In each of these instances of GenericList<T>, every


occurrence of T in the class is substituted at run time with the type argument. By substituting
the T, we have created three different type-safe using the same class.

10. What is the difference between an Array and ArrayList in C#?


An array is a collection of similar variables clubbed together under one common name. While
ArrayList is a collection of objects that can be indexed individually. With ArrayList you can
access a number of features like dynamic memory allocation, adding, searching, and sorting
items in the ArrayList.

 When declaring an array the size of the items is fixed therefore, the memory allocation
is fixed. But with ArrayList, it can be increased or decreased dynamically.
 Array belongs to [Link] namespace while ArrayList belongs to the
[Link] namespace.
 All items in an array are of the same datatype while all the items in an ArrayList can be
of the same or different data types.
 While arrays cannot accept null, ArrayList can accept null values.

Example:
// C# program to illustrate the ArrayList
using System;
using [Link];

class IB {

// Main Method
public static void Main(string[] args)
{

// Create a list of strings


ArrayList al = new ArrayList();
[Link]("Bruno");
[Link]("Husky");
[Link](10);
[Link](10.10);

// Iterate list element using foreach loop


foreach(var names in al)
{
[Link](names);
}
}
}

11. What is inheritance? Does C# support multiple


inheritance?

Inheritance means acquiring some of the properties from a master class.


Multiple Inheritance in C#

Here, class C can inherit properties from Class A and Class B. Here is an
example of inheritance:

// C# program to illustrate
// multiple class inheritance
using System;
using [Link];

// Parent class 1
class Scaler {

// Providing the implementation


// of features() method
public void features()
{

// Creating ArrayList
ArrayList My_features= new ArrayList();

// Adding elements in the


// My_features ArrayList
My_features.Add("Abstraction");
My_features.Add("Encapsulation");
My_features.Add("Inheritance");

[Link]("Features provided by OOPS:");


foreach(var elements in My_features)
{
[Link](elements);
}
}
}

// Parent class 2
class Scaler2 :Scaler{

// Providing the implementation


// of courses() method
public void languages()
{

// Creating ArrayList
ArrayList My_features = new ArrayList();

// Adding elements in the


// My_features ArrayList
My_features.Add("C++");
My_features.Add("C#");
My_features.Add("JScript");

[Link]("\nLanguages that use OOPS concepts:");


foreach(var elements in My_features)
{
[Link](elements);
}
}
}

// Child class
class ScalertoScaler : Scaler2 {
}

public class Scaler1 {

// Main method
static public void Main()
{

// Creating object of ScalertoScaler class


ScalertoScaler obj = new ScalertoScaler();
[Link]();
[Link]();
}
}
Also, C# doesn’t support multiple inheritances.
Instead, you can use interfaces to inherit the properties using the class
name in the signature.

C# Advanced Interview Questions


12. What is Boxing and Unboxing in C#?

The two functions are used for typecasting the data types:

Boxing: Boxing converts value type (int, char, etc.) to reference type (object) which is an implicit
conversion process using object value.

int num = 23; // 23 will assigned to num


Object Obj = num; // Boxing

Unboxing: Unboxing converts reference type (object) to value type (int, char, etc.) using an
explicit conversion process.

int num = 23; // value type is int and assigned value 23


Object Obj = num; // Boxing
int i = (int)Obj; // Unboxing

13. What are Properties in C#?

Properties in C# are public members of a class where they provide the ability to access private
members of a class. The basic principle of encapsulation lets you hide some sensitive properties
from the users by making the variables private. The private members are not accessible
otherwise in a class. Therefore, by using properties in C# you can easily access the private
members and set their values.

The values can be easily assigned using get and set methods, also known as accessors. While
the get method extracts the value, the set method assigns the value to the variables.

14. What are partial classes in C#?

Partial classes implement the functionality of a single class into multiple files. These multiple
files are combined into one during compile time. The partial class can be created using the
partial keyword.

public partial Clas_name


{
// code
}
You can easily split the functionalities of methods, interfaces, or structures into multiple files.
You can even add nested partial classes.

15. What is the difference between late binding and early binding in C#?

Late binding and early binding are examples of one of the primary concepts of
OOPS: Polymorphism.

For ex: one function calculateBill() will calculate bills of premium customers, basic customers,
and semi-premium customers based on their policies differently. The calculation for all the
customer objects is done differently using the same function which is called polymorphism.

When an object is assigned to an object variable in C#, the .NET framework performs the
binding.

When the binding function happens at compile-time, it is called early binding. It investigates
and checks the methods and properties of the static objects. With early binding, the number of
run-time errors decreases substantially and it executes pretty quickly.

But when the binding happens at runtime, it is called late binding. Late binding happens when
the objects are dynamic (decided based on the data they hold) at run-time. It is slower as it
looks through during run-time.

16. What are the Arrays in C#?

When a group of similar elements is clubbed together under one name, they are called arrays.

For ex. An array of tea Atea[4]: [green tea, chamomile tea, black tea, lemon tea]. The length of
the array defines how many elements are present in the array.

In C#, the memory allocations for the elements of the array happen
dynamically. This is how values are stored in an array sequentially.
Arrays in C#

A few pointers for arrays in C#:

 The memory allocation is DYNAMIC.


 Arrays in C# are treated as objects.
 The length of the array is easy to find by detecting the number of
members in the array.
 The members in the array are ordered and begin with the index
value=0.
 The array types are reference types derived from the base array type.

Syntax: < Data Type > [ ] < Name_Array >

17. What are Indexers in C#?

Indexers are called smart arrays that allow access to a member variable.
Indexers allow member variables using the features of an array. They are
created using the Indexer keyword. Indexers are not static members.

For ex. Here the indexer is defined the same way.

<return type> this[<parameter type> index]


{
get{
// return the value from the specified index of an internal
collection
}
set{
// set values at the specified index in an internal collection
}
}

18. Difference between the Equality Operator (==) and


Equals() Method in C#?

Although both are used to compare two objects by value, still they both are
used differently.

For ex.:

int x = 10;
int y = 10;
[Link]( x == y);
[Link]([Link](y));
Output:
True
True

Equality operator (==) is a reference type which means that if equality


operator is used, it will return true only if both the references point to the
same object.

Equals() method: Equals method is used to compare the values carried by


the objects. int x=10, int y=10. If x==y is compared then, the values
carried by x and y are compared which is equal and therefore they return
true.

Equality operator: Compares by reference

Equals(): Compares by value

19. What are the different ways in which a method can be


Overloaded in C#?

Overloading means when a method has the same name but carries
different values to use in a different context. Only the main() method
cannot be overloaded.

In order to overload methods in C#,

 Change the number of parameters in a method, or


 Change the order of parameters in a method, or
 Use different data types for parameters
In these ways, you can overload a method multiple times.

For ex.
public class Area {
public double area(double x) {
double area = x * x;
return area;
}
public double area(double a, double b) {
double area = a * b;
return area;
}
}

Here, the method Area is used twice. In the first declaration, one argument
is used while in the second one, there were two arguments are used. Using
different parameters in the same method, we were able to overload the
method area().

20. What is Reflection in C#?

Reflection in C# extracts metadata from the datatypes during runtime.

To add reflection in the .NET framework, simply use [Link]


namespace in your program to retrieve the type which can be anything
from:

 Assembly
 Module
 Enum
 MethodInfo
 ConstructorInfo
 MemberInfo
 ParameterInfo
 Type
 FieldInfo
 EventInfo
 PropertyInfo

21. What is the difference between constant and readonly


in C#?

A const keyword in C# is used to declare a constant field throughout the


program. That means once a variable has been declared const, its value
cannot be changed throughout the program.

In C#, a constant is a number, string, null reference, or boolean values.

For ex:

class IB {
// Constant fields
public const int xvar = 20;
public const string str = "InterviewBit";

// Main method
static public void Main()
{

// Display the value of Constant fields


[Link]("The value of xvar: {0}", xvar);
[Link]("The value of str: {0}", str);
}
}
Output:
The value of xvar is 20.
The value of string is Interview Bit

On the other hand, with readonly keyword, you can assign the variable only
when it is declared or in a constructor of the same class in which it is
declared.

Ex:

public readonly int xvar1;


public readonly int yvar2;

// Values of the readonly


// variables are assigned
// Using constructor
public IB(int b, int c)
{

xvar1 = b;
yvar2 = c;
[Link]("The value of xvar1 {0}, "+
"and yvar2 {1}", xvar1, yvar2);
}

// Main method
static public void Main()
{
IB obj1 = new IB(50, 60);
}
}

Output:
The value of xvar1 is 50, and yvar2 is 60

Constants are static by default while readonly should have a value assigned
when the constructor is declared.
Constants can be declared within functions while readonly modifiers can be
used with reference types.
22. What is the difference between String and StringBuilder in C#?

The major difference between String and StringBuilder is that String objects
are immutable while StringBuilder creates a mutable string of characters.
StringBuilder will make the changes to the existing object rather than
creating a new object.

StringBuilder simplifies the entire process of making changes to the existing


string object. Since the String class is immutable, it is costlier to create a
new object every time we need to make a change. So, the StringBuilder
class comes into picture which can be evoked using the [Link]
namespace.

In case, a string object will not change throughout the entire program, then
use String class or else StringBuilder.

For ex:

string s = [Link];
for (i = 0; i < 1000; i++)
{
s += [Link]() + " ";
}

Here, you’ll need to create 2001 objects out of which 2000 will be of no use.

The same can be applied using StringBuilder:

StringBuilder sb = new StringBuilder();


for (i = 0; i < 1000; i++)
{
[Link](i); [Link](' ');
}

By using StringBuilder here, you also de-stress the memory allocator.

C# Coding Problems
23. Write a program in C# Sharp to reverse a string?
internal static void ReverseString(string str)
{

char[] charArray = [Link]();


for (int i = 0, j = [Link] - 1; i < j; i++, j--)
{
charArray[i] = str[j];
charArray[j] = str[i];
}
string reversedstring = new string(charArray);
[Link](reversedstring);

24. Write a program in C# Sharp to reverse the order of the


given words?
internal static void ReverseWordOrder(string str)
{
int i;
StringBuilder reverseSentence = new StringBuilder();
int Start = [Link] - 1;
int End = [Link] - 1;
while (Start > 0)
{
if (str[Start] == ' ')
{
i = Start + 1;
while (i <= End)
{
[Link](str[i]);
i++;
}
[Link](' ');
End = Start - 1;
}
Start--;
}
for (i = 0; i <= End; i++)
{
[Link](str[i]);
}
[Link]([Link]());
}

25. Write a program in C# Sharp to find if a given string is


palindrome or not?
internal static void chkPalindrome(string str)
{
bool flag = false;
for (int i = 0, j = [Link] - 1; i < [Link] / 2; i++, j--)
{
if (str[i] != str[j])
{
flag = false;
break;
}
else
flag = true;
}
if (flag)
{
[Link]("Palindrome");
}
else
[Link]("Not Palindrome");

Output:

Input: Key Output: Not Palindrome


Input: step on no pets Output: Palindrome

26. Write a C# program to find the substring from a given


string.
internal static void findallsubstring(string str)
{
for (int i = 0; i < [Link]; ++i)
{
StringBuilder subString = new StringBuilder([Link] - i);
for (int j = i; j < [Link]; ++j)
{
[Link](str[j]);
[Link](subString + " ");
}
}
}

27. Write a C# program to find if a positive integer is prime


or not?
static void Main(string[] args)
{
if (FindPrime(47))
{
[Link]("Prime");
}
else
{
[Link]("Not Prime");
}
[Link]();
}
internal static bool FindPrime(int number)
{
if (number == 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
var squareRoot = (int)[Link]([Link](number));
for (int i = 3; i <= squareRoot; i += 2)
{
if (number % i == 0) return false;
}
return true;
}
2. How will you differentiate readonly, const and static variables in c#?

 const keyword allows you to declare a constant field or a constant local which you
expect not to modify at any time in the code except at the declaration time you need to
assign a value. For more visit c# const.
 readonly keyword allows you to declare a field whose values can be assigned or
modified at the declaration or in constructor only. For more visit c# readonly.
 static keywords allows you to declare the static member which belongs to the type itself
instead of object.

Fields, Properties, methods constructors, operators, local functions from C# 8 and


lambda expressions or anonymous methods from C# 9 onwards can be marked as static
inside classes, interfaces or structs. For more visit c# static.

3. What are the three characteristics of Object Oriented Programming?

There are three main characteristics of Object Oriented Programming.

 Encapsulation is considered as the first principle of OOPs. As per this principle, A Class or
Struct can specify the accessibility of its members to code outside of this class. Members
not intended to be accessed outside of this class or struct can be hidden. For more
visit Object oriented - Encapsulation.
 Inheritance is one of the three characteristics of OOPs. It allows you to create new
classes that can re-use, modify and extend the behavior defined in other classes. In
Inheritance, the class which inherits or re-use the other class members is known as
derived class and the class whose members are inherited is known as Base class.

C# does not allow multiple inheritance - means a derived class can have only
one direct base class.

Inheritance is transitive in nature means If class X inherits from class Y and class Y
inherits from class Z then class X inherits from both Y and Z. For more visit Inheritance.

 Polymorphism - It is referred to as the third pillar of Object oriented programming.


Polymorphism means "Many shapes" - more than one form of an object. It allows you to
implement inherited properties and methods in different ways across the abstractions.
C# implement polymorphism at compile time and run time. For more
visit Polymorphism.
 For Object Oriented interview questions visit Object-Oriented Questions.

3. What is the difference between in, ref and out keywords?


 in keyword is like ref or out keywords but 'in' arguments can not be modified by the
called method. 'in' arguments must be initialized before passing to the called method. If
you try to modify the value of 'in' argument in the calling method it will throw an error.
So it's like a readonly variable. For more visit in keyword.
 ref keyword causes an argument to be passed by reference and may be read or written
by the called method. To pass an argument as reference means any change to the
parameter in the called method is reflected in the calling method argument. ref
argument may be modified by the called method. For more visit ref keyword.
 out keyword causes arguments to be passed by reference and is written by a called
method. It is similar to ref keyword, except that ref requires that the variable must be
initialized before it is passed. To pass variables as out arguments, both the method
definition and the calling method must explicitly use the out keyword. For more visit out
keyword.

4. Why does c# not support multiple Inheritance?

To understand this, first you need to understand the Diamond problem:


The Diamond problem (It's also referred to as the "deadly diamond of death") is an ambiguity
that occurs when two classes B and C inherit from Class A and class D inherits from both B and
C. If a method in class D calls a method defined in A(and does not override the method), and B
and C have already overridden that method differently, then from which class does it inherit: B
or C?

5. What is method shadowing or method hiding in C#?

Shadowing is also known as method Hiding in C#. Shadowing is a [Link] concept. It hides the
base class method implementation. It can be achieved using the 'new' keyword. If a method is
not overriding the derived method that means it's hiding it.

Override keyword is used to provide a completely new implementation of a base class method
or extend base class method (which is marked 'Virtual') in the derived class. While the New
keyword just hides the base class method, not extends it.
If you think you need a different implementation of the same function as provided by base
class, then you can hide the base class function implementation in child class.

class BC
{
public void Display()
{
[Link]("BC::Display");
}
}

class DC : BC
{
public void Display()
{
[Link]("DC::Display");
}
}

class Demo
{
public static void Main()
{
DC obj = new DC();
[Link]();
}
}

Output : DC:Display

On compilation the above program will throw a warning which says [Link](11,15): warning
CS0108: '[Link]()' hides inherited member '[Link]()'. Use the new keyword if hiding
was intended. [Link](3,15) So modify the code as below.

class DC : BC
{
new public void Display()
{
[Link]("DC::Display");
}
}

6. How will you differentiate var, object and dynamic keywords in C#.

Let's take a look at this example to understand the difference.


class Program
{
static void Main(string[] args)
{
var x = 10;
object y = 20;
dynamic z = 30;

x = "test"; // Error - Cannot implicitly convert type 'string' to 'int'

y = "test";
y = y - 10; //Error Operator '-' cannot be applied to operands of type 'object' and 'int'

z = "test";
z = z - 10;
[Link]("{0},{1},{2}",x,y,z);
[Link]();
}

void display(var x){} // Error CS0825 - The contextual keyword 'var' may only appear within a in
local variable declaration or script code.

void display(object x){}

void disp1(dynamic x){}


}

 var was introduced with C# 3.0, Variables declared at method scope level can have
implicit type 'var'. var types are initialized at the time of declaration only and can store
any value. Compiler determines the type of var type so it is similar to strongly typed.
You can use a var type in the same scope where it is defined - refer example. Type
casting is not required as the compiler has all information to perform operations. You
can use a var type for constructor invocation expressions, anonymous type etc. For
more visit var.
 object is the part of C# 1.0, It is the base class of all types in .NET framework so it can
store any type. Compiler has little information about the type. You can pass object type
as method argument and can return object type from a method as in the above
example. object types need type casting to perform operations and can cause the
problem at run time if type casting is not performed. For more visit object.
 dynamic was introduced with C# 4.0, Use of dynamic keyword with variable and it's
members bypass the compile time type checking instead it resolves all operations at the
runtime. You can pass dynamic type as method argument and method also can return
dynamic type - refer example. Casting is not required as operations are resolved at
runtime but you should have correct member information to use dynamic types. For
more visit dynamic.

7. Can Virtual or Abstract members be declared private in C#?

No, it will throw a compile time error.

virtual void display() // will throw error here


{
// Implementation

8. What is Boxing and Unboxing in C# ?


 Boxing - When a value type is converted to the 'object' type or to any interface
type implemented by this value type is known as Boxing. When CLR performs
boxing on a value type it wraps the value inside a [Link] instance and that
value is stored on a managed heap.
 UnBoxing - When a value type is extracted from the 'Object' is called Unboxing.

Boxing is performed implicitly and Unboxing is implemented explicitly. Boxing and


Unboxing example:
int a = 13;
// The below line assigns the value of int a to object o, it's
boxing.
object o = a;
Now you can assign the value of o to integer a, it's unboxing.
o = 13;
a = (int)o; // unboxing

For more visit Boxing and Unboxing in C#.

9. What is Method Overloading in C#?

Method Overloading is a way to implement polymorphism - you are going to have more than
one form of a method. You can implement method overloading by defining two or more
methods in a class with the same name but different method signatures.

Method Signature includes number, sequence and type of parameters not the return type of
method. Method overloading example:
void check(int x)
{
// Implementation
}
void check(float x)
{
// Implementation
}
void check(int x, int y)
{
// Implementation
}
In the above example method name is the same 'check' in all three cases but method signature
is different.

10. What is Value Type and Reference Type in C#?

C# has mainly two categories of the types.


 Value types - A Value type variable holds an instance of the type and when you
perform any assignment only an instance of the type is copied, not the reference of that
instance. By default, when you pass an argument to a method, only variable value is
copied. Value types include the following:
o All numeric data types
o Boolean, Char, and Date
o All structures, even if the members of structure are reference types
o An Enum type, since the underlying type of enum is always SByte, Short,
Integer, Long, Byte, UShort, UInteger, or ULong.

For more Value Types in C#.

 Reference types - Variables of reference types contain the references (memory


address) to an instance of the types.
A reference type holds the address of a memory location that holds the actual data
of the variable. So operations you perform on one variable can affect the object
referenced by the another variable.
C# offers some keywords to declare reference types including: class, interface,
delegate, record and provides some built-in reference types like dynamic, object,
string.
For more Reference Types in C# and Value Types and Reference Types in C#.

10. What are the new features in C# 8.0?

To know more about C# 8.0 new features visit What's new in C# 8.0

11. How will you differentiate Abstraction and Encapsulation in C#?

 Abstraction is to create the prototype of relevant attributes and interaction of an


entity in the form of classes. This Prototype defines an abstraction representation
of a concept. For example, A BankAccount base class creates an abstraction or
defines the behavior for the Bank Account concept. Now you can create any type
of bank account like saving, just by deriving your new class 'SavingAccount' from
this 'BankAccount' base class.
 Encapsulation is the hiding of the functionality and internal state of an object
from the code outside of this class and allows access through a public set of
properties or functions. For Example, the BankAccount class can contain some
private members to hide the data from the code outside of this 'BankAccount'
class.
 Abstraction can be implemented using Abstract classes and Interface whereas
Encapsulation can be implemented using access modifiers such as public, private,
protected etc.
 Abstraction helps to solve the problems at design level using Abstract classes or
Interfaces while encapsulation helps to solve problems at implementation level
using access modifiers.

For more visit Abstraction vs Encapsulation and Abstraction vs Encapsulation in C++.

12. Differentiate Abstract class and Interface in C#? Explain the usage of interface?

Abstract class and Interface allows you to define an abstraction in C#. But both have some
differences.

 Abstract class provides both declaration and implementation but Interfaces have only
declaration.
 When you want to achieve multiple inheritance then you should use Interface not
Abstract class because in C#, a class can inherit from one class only but from more than
one interface.
 Abstract class contains constructors while Interface does not.
 Interfaces have only public members whereas abstract classes can contain public,
private protected modifiers.
 Abstract class can provide complete, partial or no implementation whereas Interface
provides only declaration.
 Performance wise, Abstract class is fast as Interface needs to identify the actual method
implementation which takes some time.
 Interface provides you the ability of a class whereas An abstract class gives you the
identity of class.
 Abstract class allows you to define and implement some common functionality which
can be used by many child classes but Interface gives you common method signatures
that can be implemented differently as per requirement.
 Abstract class can provide default implementation for any newly added method and all
code will work properly but in case of Interface you need to implement that new
method in all the classes using that interface.
 Members of Interface can not be static but complete members of Abstract class can be
static.
 Interfaces allow you to create Mocks easily in unit testing while Abstract class needs
extra coding.

For more visit Abstract class vs Interface C#.

13. What is Polymorphism? Explain the static and Dynamic Polymorphism in C#?

Object-oriented programming has mainly three pillars, Polymorphism is one of them after
encapsulation and inheritance. It has special meaning - "many shapes" and has two aspects:
 At run-time, derived class objects may be considered as base class objects in places such
as method parameters and collections or arrays. When this polymorphism happens,
declared and run-time types of object are different. For example,

 public class Shape
 {
 }

 public class Circle : Shape
 {
 }
 public class Rectangle : Shape
 {
 }
 var shapes = new List
 {
 new Rectangle(), new Triangle(), new Circle()
 };
 Base classes may have virtual members which can be overridden by the derived
class with their own definition and implementation. At the time of execution,
When client code calls the method, the override method is executed because CLR
looks up the run-time type of object rather than of the compile-time object. In your
code you can cause a derived class method to be executed by calling a method of
base class as below.

 A o1 = new A();
 [Link]();
 B o2 = new B();
 [Link]();
 A o3 = new B(); // here
 [Link](); // derived class method will be executed by calling base
class method

MSDN does not provide any information regarding static and dynamic polymorphism,
rather than just two distinct aspects which are mentioned in above two points. Some
authors consider function and operator overloading as static polymorphism, while some
authors describe generic programming by parametric polymorphism So all these are
different points of view of authors to explain the polymorphism. But MSDN considers
dynamic polymorphism as a more convenient definition of Polymorphism.
For more about Polymorphism visit Polymorphism.

14. Print the output of the below program? Error Line will throw any error in below code?

class A
{
public virtual void display()
{ [Link]("A - display method"); }
}
class B:A
{
public override void display()
{ [Link]("B - display method"); }
}
class Test
{
static void Main()
{
A obj = new A();
[Link]();

A obj1 = new B();


[Link]();

B o = new B();
[Link]();
// B ob = new A(); Error Line
[Link]();
}
}
Output: 'Error Line' will throw error - "Cannot implicitly convert type 'A' to 'B'. An
explicit conversion exists (are you missing a cast?)".
Output will be as below.
A - display method
B - display method
B - display method

16. Can Abstract class have a constructor in C#? Below code will compile or not, or it will give
any error in Error line 1 or 2.

class A
{
public virtual void display()
{
[Link]("A - display");
}
public virtual void disp()
{
[Link]("A - disp");
}
}
abstract class ab :A
{
public ab()
{ }
public abstract override void display(); Error Line 1

public sealed override void disp() Error Line 2


{
[Link]("disp is sealed now.");
}
}
Solution: Abstract class can contain the constructor. Constructor is used to instantiate the
class instance members in C#.
The above code will compile successfully. In C#, we can
add Abstract and Sealed keywords with the override keyword.

17. What is volatile keyword in C#?

In C#, volatile keyword indicates that multiple executing threads which are executing at
the same time can modify the value of a field. The fields which are declared volatile are
observed by all the threads for volatile writes by any other thread in the same order in
which it was performed. All reads and writes to memory locations of volatile fields may
be rearranged by the compiler, the runtime and even hardware for performance reasons.
For more visit C# volatile.

18. What is the use of the sealed keyword in C#?

In C#, a sealed modifier is used to prevent your class from being inherited by other
classes. When you want that other class should not inherit from your class then you can
add a sealed modifier to it. You can create sealed classes in C# as below.
class C {}
sealed class D : C {} // other classes will not be able to inherit from
class D.
You can use a sealed modifier to methods and properties in your class which are
overriding methods and properties from base class. Using this way other classes will
derive from your class and will not be able to override sealed methods and properties. For
more visit C# sealed.

19. Explain string interpolation in C#.

In C#, String Interpolation provides the capability to create formatted strings with
convenient and readable syntax. The $ special character allows you to create an
interpolation string that might contain interpolation expressions. When the interpolation
string resolves it replaces the interpolation expression with string representation of the
interpolation item. String Interpolation is the feature of C# 6. Example:
var name = "Microsoft";
[Link]($"Hello {name}"); // O/P: Hello Microsoft

For more visit C# String Interpolation.

20. What is the difference between abstract and virtual keywords ?

Both virtual and abstract are the modifiers in C#. They have different use cases.
 virtual keyword allows you to override any method, property, event declaration or
indexer in derived class. It gives the capability to modify the implementation of
the base class virtual member in derived class. Virtual members provide default
implementation that you can modify in a derived class. When you invoke a virtual
member, the run-time type of the object is considered for an overriding member.
For more visit virtual C#.
 abstract keyword indicates that the base class has incomplete implementation or
something missing that you need to complete in derived class. You can use the
abstract modifier with class, methods, properties, events and indexers.
It is necessary to complete the implementation of abstract members of base class.
Only an abstract class can contain abstract members and non-abstract members
as well.
For more visit abstract C#.

20. What are the new features in C# 7.0?

To know more about C# 7.0 new features visit What's new in C# 7.3

21. What is Covariance and Contravariance in C#?

Fore more Covariance and Contravariance in C#

22. What will be the output here? or will it throw any error?

public void display()

{
int x = 0;
int y = 10;
try
{
int z = y / x;
}
catch (Exception)
{
throw;
}
catch (DivideByZeroException)
{
throw;
}
finally
{
}

}
23. What points (related to try, catch and finally) you should keep in mind while implementing
exception handling in C#?

24. What is Generics in C#? What are the benefits of Generics?

25. What is IDisposable Interface in C#? How to implement the dispose method?

26. Explain Dispose Pattern in C#.

27. How does Garbage Collection work in C#? Explain Generations.

28. What is using statement in C#?

In C#, All unmanaged resources and class libraries must implement


the IDisposable or IAsyncDisposable interface.
The using statement ensures the correct use of IDisposable or IAsyncDisposable objects.
When the object's lifetime is limited to a single method then you should use the 'using'
statement to declare and instantiate disposable objects. An object declared inside a using
statement can not be modified or re-assigned meaning it is read-only. It disposes the
object in case of any exception or it's equivalent to try-finally implementation.
using statement example:
string message=@"Hello I am good , first line
How are you, second line
I am fine third line";

using var reader = new StringReader(message);


string? line;
do {
line = [Link]();
[Link](line);
} while(line != null);
For more visit using statement.

29. What are Finalizers in C#? Explain SupressFinalize() method.

30. Print the output of this program?

int a = 0;
try
{
int x = 4;
int y ;
try
{
y = x / a;
}
catch (Exception e)
{
[Link]("inner ex");
//throw; // Line 1
//throw e; // Line 2
//throw new Exception("divide by 0"); // Line 3
}

}
catch (Exception ex)
{
[Link]("outer ex");
throw ex;
}

Let's see the output:

 Output will be - "inner ex" as we are not throwing anything from the inner catch
block, so the outer catch block will not execute.
 If we uncomment 'Line 1' then output will be - "inner ex" and "outer ex" and outer
catch will throw an exception.
 If we uncomment 'Line 2' then output will be the same - "inner ex" and "outer ex"
and outer catch will throw an exception.
 If we uncomment 'Line 3' then output will be - "inner ex" and "outer ex" but the
exception message in outer catch will be different, overridden by a throw message
from inner catch block.

31. Explain about String Immutability in C#.

Once you create a String object in C#, It can not be modified. When you perform any operation
like appending then you get a new instance of a modified String object instead of modifying the
actual instance value. So String Objects are immutable in C#. If you are planning to perform
many append operations on a string object then use StringBuilder class.
For more visit Immutable String in C#.

31. How to compare two String Objects in C#?

You should use the Compare method to determine the relationship of two strings in sorting
order and if you want to test for equality of two strings then you should Instance Equals or
static Equals method with a StringComparison type parameter.
For more about string operations visit String in C#.

32. What is the difference between the Equality operator == and Equals() method in C#?

33. What is the use of new keyword apart from creating a new object in C#?

34. What are the extension methods in C#?


34. Explain the Lambda expressions in C#?

34. What are the anonymous methods in C#?

35. Explain Partial class and methods.

36. What are the different ways to pass parameters in C#?

37. How will you differentiate EXE and DLL files?

38. What is the DLL hell Problem?

39. Explain the concept of Parallel Processing, Concurrency, and Async Programming in .NET?

For more visit Parallel Processing, Concurrency, and Async Programming in C#.

40. What is async and await in C#?

Both async & await keywords are used to implement asynchronous operations in C#.
These operations could be either I/O bound (such as web service taking time to download
some content or file) or CPU bound (any expensive calculation by CPU).
You can mark a method, lambda expression or anonymous method as async. Async
method should have at least one await statement to perform operation asynchronously
and it returns Task means - the ongoing work. When the control reaches the awaited
expression, the method is suspended until the task gets completed because we are waiting
for the result of the awaited task.
public async Task<int> ExampleMethodAsync()
{
//...
string contents = await [Link](requestUrl);
}
For more about Asynchronous programming visit Asynchronous programming with
async and await and async await C#.

44. Explain C# 6.0 new features.

C# 6.0 has many new features. For more visit What's new in C# 6.0

45. What is Deep copy and Shallow copy?

46. What is the use of yield keywords in C#?

47. How User-defined conversions work in C#?

47. How User-defined conversions work in C#?


48. Differentiate Action vs Func in C#.

class Test
{
// Func Example
public string CreateNamefromName1()
{
return CreateName(GetName1);
}
public string CreateNameFromName2()
{
return CreateName(GetName2);
}
private string CreateName(Func<string, string, string> createName)
{
var name1 = "hello";
var name2 = "testing";
return createName(name1, name2);
}

private string GetName1(string arg1, string arg2) => $"{arg1}-{arg2}";


private string GetName2(string arg1, string arg2) => $"{arg1}::
{arg2}";

1. What is a Datatype?
A: Datatype means the type of data which can be stored in a variable. It
also identifies the way memory is allocated to a variable as well as the
operations that can be performed on the same variable.

2. What are Nullable types?


A: The value types that can accept a null value are called the Nullable
types.

3. What is (??) operator in C#?


A: The ?? operator is specifically known as the null coalescing operator,
and is used for defining a default value for a nullable value type.
4. How to check that a nullable variable is
having value?
A: To check whether a nullable variable has value or not, HasValue
property is used.

5. What are the differences between Object and


Var?
A: The introduction of object was done with C# 1.0, while for Var it was C#
3.0. You can use object when you want to store several types of values in
a single variable; while Var is used when you are not sure about the type
of assigned value. Object can be passed as a method argument, while the
same cannot be done with Var.

6. What is the ref keyword in C#?


A: The ref keyword is known for causing an argument that is passed by
reference and not value.

7. What is the params keyword in C#?


A: The params keyword allows a method parameter to obtain a huge
number of arguments. These large number of arguments are changed with
the help of the compiler into elements in a short-term array.

8. What do you mean by operators in C#?


A: An operator is used as a symbol that tells the compiler about the kind of
operations that can be performed on an operand.

9. What are the different types of operators in


C#?
A: There are a total of seven operators in C#, which include:

 Arithmetic Operators: These are the kind of operators that are used for
performing arithmetic operations.
 Relational Operators: These operators are used for comparing values.
These always result in true or false (>,<,!=, etc).
 Logical/Boolean Operators: These operators are also used for comparing
values. These also always result in true or false (! , &&).
 Bitwise Operators: These operators perform a bit-by-bit operation.
 Assignment Operators: These operators help in assigning a new value to
the variable.
 Type Information Operators: These operators provide information about
a certain type.
 Miscellaneous Operators: ?: , => , & , && , *

10. What is ternary operator in C#?


A: A ternary operator is used for a conditional expression that returns a
Boolean value. It is a short form of if-else.

Register to Learn:- C# in Hindi

11. What is the static keyword mean in C#?


A: Static keyword helps to specify a static number. This means static
members are not tied to a particular object, rather common to all objects.

12. What do you mean by Typecasting in C#?


A: Typecasting in C# is a mechanism that covers a certain type of value to
another value. It is only probable when both the data types are well-suited
with each other.

13. What are the different types of casting in


C#?
A: The different types of casting in C# are explicit conversion and implicit
conversion. Explicit conversion means conversion from a larger data type
to a smaller data type. Implicit conversion is just the opposite in which
smaller data types are converted into larger data types.

14. What is an Out keyword in C#?


A: Out keyword is used to pass the arguments to methods in the form of a
reference type. It is mostly used when multiple values are returned by a
method.

15. Can out and ref be used for overloading as


the different signature of method?
A: That cannot be done. Even when ref as well as out is treated in a
different way at runtime, they are treated the same way during compile
time. Therefore, it cannot be loaded with similar kinds of arguments.

16. What do you mean by value type and


reference type?
A: Actual values are stored by a value type variable; while references of
actual values are stored by a reference type variable.

17. What is a safe and unsafe code in C#?


A: A safe code is the one that runs by the management of CLR; and, an
unsafe code does not run by the management of CLR.

18. What is boxing and unboxing in C#?


A: Implicitly converting a value type into a reference type is called boxing.

Example: int variable = 15

object boxingvar = variable

Explicitly converting the same reference into value type is called


unboxing.

Example: int variable = 15

object boxingvar = variable

int unboxed = (int)boxingvar


19. What is upcasting and downcasting?
A: Upcasting is implicitly converting the derived classes into a base class.
Downcasting is just the opposite in which the base class is explicitly
converted into a derived class.

20. What do you mean by static members?


A: Static members use static keywords. These can be called with class
name.

21. What is the base class in .NET framework


from which all the classes have been developed?
A: [Link]

22. What is a static class?


A: A static class is a class in which the CLR fills it with memory automatically during code
execution.

23. When to use a static class?


A: A static class is significant if you want to provide common utilities such as configuration
settings, driver functions, and many more.

24. What are sealed classes in C#?


A: Sealed classes are the special kinds of classes that are used to stop
inheritance.

25. Can multiple catch blocks be implemented?


A: Multiple catch blocks cannot be implemented. Once you execute the
proper catch code, the control is moved to the final block. After this, the
code following the final block is implemented.

26. What is an object pool in .NET?


A: An object pool can be called a container with objects that can be used.
It tracks the object that is in use at present.

27. What do you mean by partial method?


A: A partial method is basically a special method in a partial class, which is
also called a struct. One part of a partial class has the only partial method
declaration, which means signature, as well as the other part of the same
struct, may have an execution.

28. What are the different ways a method can be


overloaded?
A: Methods can be overloaded with the help of various types of data for a
parameter, several orders of parameters, and a varied number of
parameters.

29. What is serialization and its main purpose in


C#?
A: Serialization in C# means converting an object into a stream of bytes.
This further helps in storing the object into memory or fill in the form of
XML, JSON, etc. Serialization helps in saving the state of an object so that
it can later be recreated as per requirement.

30. What is reflection in C#?


A: Reflection is used for observing objects and their types. Reflection
namespace has classes that enable you to get information about modules,
assemblies, and types.

31. When should reflection be used?


A: Reflection can be used to create an instance of a type. It is also used to
dynamically fix the type to an object that exists.

32. What do you mean by exceptions in C#?


A: These are unpredicted errors that take place during the implementation
of a program. This is mostly caused because of inappropriate use of user
inputs, system errors, to name a few.

33. What is the role of [Link] class?


A: .NET framework provides [Link] class to handle various
types of exceptions that take place. The exception class is the basic class
among the other exception classes.

34. What is exception handling?


A: Exception handling is a way of capturing run-time errors as well as
handling them appropriately. Try-catch blocks, as well as throw keywords,
are used to do it.

35. What are the various types of serialization?


A: The several types of serialization include XML serialization, Binary
serialization, and SOAP serialization.

36. What are Delegates?


A: Delegates are the reference types that help in holding the reference to
a method class. Methods that have the same signature as delegates can
be allotted to delegates.

37. What is Polymorphism in C#?


A: Polymorphism is the ability of a programming language to the objects in
various ways, which totally depend on their data type. Polymorphism is of
two types, which include Compile-time polymorphism and Runtime
polymorphism.

Read more:- What is Polymorphism In C++

38. What are the uses of delegates in C#?


A: Delegates have several uses. Some of them are Callback Mechanism,
Multicasting, Asynchronous Processing, and Abstract and Encapsulate
methods.

39. What is the property in C#?


A: Property is a wrapper around a field. Property is used for assigning as
well as reading the value from the field with the help of set and get
accessors. The property can be created for various fields such as private,
public, protected, and internal.

40. What are the uses of the property?


A: The uses of the property are validating data before allocating it to a
field and logging all access for a child, when you need it.

41. What is the difference between “as” and


“is” operators in C#?
A: “as” operators are used to cast the object to class. “is” operators are
used to check the object with type. This will then return a Boolean value.

43. What is an indexer in C#?


A: An indexer allows a struct instance to be indexed just like an array.

44. How encapsulation is implemented in C#?


A: Implementation of encapsulation is done by using access specifiers. An
access specifier helps in defining the visibility of a class member.

44. What are collections in C#?


A: Collection in C# is a set of relevant objects. It is a class; therefore, a
new collection must be declared before elements are added to that
collection.

45. What are Generics in C#?


A: Generic is a class that enables you to define classes as well as methods
by using a placeholder. Generics were part of version 2.0 of the C#. The
intention of using Generic is to enable type to be a parameter to classes,
methods, and interfaces.

46. What is Anonymous type in C#?


A: Anonymous type allows the users to create a new type without the need
to define them. This is a way to define read-only properties in a single
object without defining the type explicitly.

47. Can you briefly explain Thread Pooling in


C#?
A: Thread Pool in C# is basically a collection of threads. Those threads are
used for performing tasks without making a disturbance in the
implementation of the primary thread. Once a thread from the thread pool
completes implementation, it returns to the thread pool.

48. What is Multithreading in C#?


A: Multithreading enables users to perform more than one operation
simultaneously. To perform threading in C#, The .NET framework
[Link] namespace is used.

49. What are the different states of a Thread in


C#?
A: The various states of a Thread in C# include:

 Aborted – This means the thread is dead but not stopped


 Running – This means the thread is implementing
 Stopped – This means implementation has been stopped by thread
 Suspended – This means the thread has been put off

50. How can the singleton design pattern in C#


be used?
A: The singleton design pattern is used in C# in a situation when the class
has one instance and the access has been provided widely.

51. What are the different types of decision-


making statements in C#?
A: There are various types of decision-making statements that are
included in C#. The statement types can be if statement, if-else
statement, switch statement, and if-else-if statement.

52. Which one is better/faster, switch or if-else-


if statements, and why?
A: Among these two, the switch statement is considered faster than the if-
else-if statement. This is because the switch does not check earlier
statements, but in case of if-else-if each condition has to be checked.

53. What is the goto statement?

A: A goto statement, provides a labeled statement with the control of the


program. For this, the statement has to be within the scope of the goto
statement.

54. What is the return statement in C#?

A: The function of a return statement in C# is to terminate the method’s


execution where it appears, and the control is retrieved to the calling
method.

55. What is the jump statement in C#?

A: The jump statement in C# is used to transfer the program control from


one point to another point in the program.

56. What does the throw statement do?


A: The throw statement is used for throwing an exception, indicating an
error encountered while executing the program.
57. What do you mean by an array and what are the different types of the array in C#?

A: A collection of similar elements accessible through a numeric index is called an array. You
can have one-dimensional array, two-dimensional array, and jagged array.

58. What is a multi-dimensional array?


A: A multidimensional array contains more than one level or dimension of
array such as 2D and 3D array

int[,] arr2D = new int[6,8];// declaration of 2D array

arr2D[0,0] = 1;

59. What is a jagged array?

A: An array, with elements consisting of arrays of different sizes and dimensions, is called a
jagged array.

60. What do you mean by an object in C#?

A: A real-world entity having behaviors and attributes, an object in C# represents the class it
belongs to. For its member functions, it carries out memory allocation.

61. What is a constructor?

A: It is a special function having the same name as its class. Whenever an object of a class is
created, the constructor is invoked.

62. Why does the static constructor have no


parameter?
A: As the static constructor is invoked automatically and called through
the Common Language Runtime (CLR). It can’t be directly called and that’s
why it doesn’t have any parameters.
63. Why can you have only one static
constructor?
A: Constructors must be overloaded to define multiple constructors for any
given class. For this parameterized constructors must be defined that
can accept outside parameters. The static constructors cannot be called
directly and only through CLR which can’t pass the parameter to the
parameterized constructor.

64. What is a destructor in C#?

A: A special member function that is utilized for releasing the unmanaged resources allocated
by the object. It has the same name as its class name following the ~(tilde) sign, and it can’t be
called explicitly.

65. What purpose does the “using” statement serve in C#?

A: Using statement fetches the resources that are specified, followed by using it, and then
cleaning up through the dispose method when the statement is completely executed.

66. What is the purpose of an access modifier?


A: The access modifier can be utilized to specify the accessibility of the
class member.

67. Can destructors have access modifiers?


A: As the destructors are directly called by the compiler, it cannot have
access modifiers.

68. What is enum and when should it be used?


A: The enum is a value type that is used to store enumerators which is a
list of named constants. Enum can be used to define static constants and
constant flags.

69. What is the difference between class and


structure?
A: Class is a reference type while the structure is a value type. Class can
have a destructor while for a structure having a destructor is not possible.
Class can have both parameterized constructor and default, while a
structure can only have a default.

70. What is the difference between direct cast and ctype?

A: A direct cast is utilized for conversion of object type, that requires


runtime similar to the specified type in direct cast. Ctype is instead used
when converting the conversion defined for the expression and type.

71. When should you use Async and Await?

A: Async and Await are used in C# to create asynchronous methods.


Asynchronous programming processes can run without any dependency on
other processes including main processes.

72. What is Managed and Unmanaged code?

A: Managed code is written to get the services of managed runtime


environment execution such as the CLR within the .NET framework.
Unmanaged code on the other hand is executed directly by the operating
system, providing low-level access and direct hardware access to the
programmer.

73. Explain Namespaces in C#?


A: Namespace is utilized for organizing large code projects. You can create
a custom namespace and also create them within another namespace
which is known as nested namespaces.

74. What is a Deadlock?


A: Deadlock is an occurrence where two or more processes are waiting for
the other to finish, and therefore a process cannot finish its execution. It is
commonly found in multi-threading.

Going through these questions is a sure way to feel prepped up about your
upcoming interview. It is also a great resource even if you do not have an
interview lined up but wish to grasp the basics of the language and
building a strong foundation for your career.
Read More Interview Questions
 SQL Interview Questions
 Python Interview Questions
 Java Interview Questions

FAQs Related to C#
Q: Is C# worth learning?

A: Learning C# is actually valuable. You can build any kind of application if


you have learned C#. The applications that can be built are web services
and web applications, games, console applications, desktop applications,
IoT applications, windows services, AI applications, native mobile
applications, cloud applications, and reusable libraries.

1. What is the difference between Public, Static, void?


 Static: When using Static, the object is not required to access static
members.
 Public: This keyword specifies that the method of the class can be
accessible publicly
 Void: This keyword specifies that the method does not have a return
type

2. What is C# also mention some features of C#.

C # is the best language for writing Microsoft .NET applications. C # gives


rapid application development in Visual Basic the power of C ++. The syntax
is similar to C ++ syntax and meets 100% OOP requirements as follows:

 Abstraction
 Encapsulation
 Polymorphism
 Inheritance

3. Please elaborate on the reason why we use C#


Choosing C # as your first programming language helps you understand
many concepts quite easily. Setting up a Hello project is very intuitive. As
one of the most popular programming languages, you have a number of
documents on the internet that can help you troubleshoot and correct errors
in your code.

One of the main selling points for .NET (C #) is that Microsoft provides a wide
range of powerful tools that can help programmers develop better
applications. By far the most important of all these tools in Visual Studio.
Visual Studio is a very powerful and rich integrated development
environment (IDE) that provides a large number of tools to support
application development.

Through C# we can develop a number of applications like

 Desktop applications
 Web applications
 Mobile applications
 Games

4. What are the advantages of C#?


 Simple and fast
 High scalability
 Cross-platform
 No buffering

5. What are the different types of comments in C#?


 Single line comment denoted with //
 Multiline comments denoted with /*
 XML comment denoted by ///

6. Elaborate the code compilation process in C#?

These steps involved in the C# compilation process

 Clubbing newly created code


 Executing assembly
 CLR
7. List down the available access modifier in the C#?
 Public
 Private
 Protected
 Internal
 Protected internal

8. Mention the different IDE’s provided by Microsoft?


 Visual Studio
 Visual web developer

9. Distinguish between continue and break statement?

Using break, you can jump over the block of code while using continue you
can jump over the iteration and continue the execution

10. What are the different approaches to pass the


parameter to a function?
 Value type parameter
 Reference type parameter
 Output parameter

11. Distinguish between finally finalize block?

Finally block called after the execution of try catch block while finalize
called just before the garbage collection

12. What is managed and unmanaged code?

Managed Code is code generated by the .NET compiler. It does not depend on the target
computer as it is performed by CLR (Common Language Runtime) and not the operating system
itself. The CLR and admin code do not provide many benefits to developers, such as waste
collection, type checking, and exemption management.

On the other hand, the Unmanaged Code is compiled directly with the built-in machine code
and depends on the architecture of the target machine. It is executed directly by the operating
system. For unmanaged code, the developer must consider memory usage and allocation
(mainly due to memory leakage), type protection, and manual exceptions. In .NET, Visual Basic,
and the C # compiler create managed code. To get unmanaged code, the application must be
written in C or C ++.

13. Differentiate between class and object?

A class is a description of an object and what a class representation is an object. We can think of
the class as a model for the object: it describes all the properties, methods, states, and
behaviors that the implementing object will have.

An object is an instance of a class, and a class does not become an object until an instance is
created. There can be multiple instances of objects based on a class, each with different
properties.

14. What is an abstract class?

An abstract class cannot be instantiated. It only allows other classes to inherit from it, but
cannot be instantiated. The advantage is that it uses certain hierarchies for all subclasses.
Basically, it is a type of contract that forces all subclasses to maintain the same hierarchies or
standards.

15. What is a sealed class?

Sealed classes are used to limit the inheritance function of object-oriented programming. When
a class is defined as a sealed class, the class cannot be inherited. Visual Basic .NET uses the non-
transferable keyword to seal. If a class is derived from a sealed class, the compiler returns an
error.

16. Elaborate the fundamentals of oop?

 Inheritance
 Abstraction
 Polymorphism
 Encapsulation

17. How can we inherit one class from another class?

The colon (:) is used as an inheritance operator in the C#. place the colon and class name

18. What is method overloading?


Create the number of methods with the same name and type and class but
with different parameters is known as method overloading.

19. Differentiate between method overloading and


overriding?

Method overload

 Create the number of methods with the same name and class but with
different parameters
 It is performed within class
 The parameter must be the same

Method overriding

 If the definition of the derived class change method behavior should be


changed
 Occurs in two classes
 A parameter must be different

20. Define an interface?

Like a class, Interface can have methods, properties, events, and indexers as
members. But the interfaces only contain the membership statement. The
implementation of the interface members is given by the class that implicitly
or explicitly implements the interface.

21. Distinguish between class and struct?

Class Structure
Classes are a kind of reference value type
All reference types are arranged in a smaller memory stack memory used to assign the valu
The class has unlimited functionality Struct has limited functionality.
commonly used in large programs Used in the small program
Classes can be constructive or destructive A structure does not have a construc

22. Differentiate between virtual and abstract


method?
Virtual:

 It must have a default implementation


 It is overridden by the keyword override
 The virtual method has code

Abstract:

 It does not have any implementation


 It forces the derived class to override the method
 They don’t have actual code in them.

23. Illustrate the namespace in C#?

A namespace is a collection of classes and another namespace. We are using


the namespace to organize our project.

24. Define the 'using' statement?

Basically, with this keyword, we add a different namespace to our project.


For the usage for their classes. In the case of C#, the System namespace is
where many useful things are described. One of these useful things given C#
is that the Console class can let me write things that can appear on the
screen ahead of the user to this as Console I even have to inform the
compiler I'm using the System namespace. The means that if I ask
something by a specific name the compiler will look in the System to
ascertain if there's anything matching that name

25. Define boxing and unboxing?

Converting the value type into a reference type is known as boxing. While
explicit conversion of the same type is known as unboxing

26. What is an array?

An array is used to store the multiple variables of the same data type. The
array always starts from the zero indexes. Each index in the array holds a
value.
<data type> [] <identifier> = new <data type>[<size of array>];

27. What is a jagged array?

A jagged array reference to an array of array. It is a nested array whose


elements are the arrays. The element can be of different size dimensions.

28. Distinguish between array and array list?

Array:

 Use the vector array for storing the element


 The size of the array must be defined
 Typecasting is not necessary

Array List:

 Used linked list to store the element


 There is no need to specify the size
 Typecasting is necessary

29. What is collection?

The collection is work as the container for the instance of the other classes
every class implement collection interface

30. Illustrate the serialization?

It is a process that involves the conversion of one code of block into its
binary format.

31. What is parsing?

Conversion of string into to other datatypes is known as parsing for example

String a = “123”;

Int data = [Link](a);


32. Explain about delegate?

A delegated object contains a reference to a method. Delegates in C # are the same as function
markers in C or C ++. A delegated object is a reference type variable that is used to contain a
reference to a method. The reference can be changed by runtime owned by a delegated object,
a delegated object can contain many reference functions, also known as call list, which refers to
functions in a FIFO sequence, we can refer to new functions in this list at runtime of += operator
and can be deleted by -= operator.

33. Distinguish between string and StringBuilder?

String:

 It is immutable
 Cannot perform a variety of operations.

StringBuilder:

 It is mutable.
 Support variety of operations on string builder.
 The new memory is not allocated.

34. What is LINQ?

LINQ is an acronym for Language Built-in Query and was introduced with
Visual Studio 2008. LINQ is a set of functions that extends query functions to
the syntax of the .NET language by adding sets of new standard query
operators that allow data manipulation, independently of the data source.
Supported data sources are .NET Framework collections, SQL Server
databases, [Link] datasets, XML documents, and any object collection
that supports IEnumerable or the generic IEnumerable interface <T> in both
C # and Visual Basic. In short, LINQ bridges the gap between the object
world and the data world.

35. What is garbage collection?

Garbage collection is a low-priority process that acts as an automated memory manager that
manages the allocation and release of memory to applications. Each time a new object is
created, the common language execution allocates memory time to that object from the
managed stack. As long as free memory space is available on the managed stack, the runtime
continues to allocate space for new objects. However, memory is not infinite, and when an
application fills the memory space in the heap, garbage collection kicks in to free up memory.
When the garbage collector performs a collection, it searches for objects in the managed stack
that are no longer in use by the application and takes the necessary steps to restore memory.
Garbage collection stops all running threads, finds any objects on the stack that cannot be
accessed by the main program and deletes them. Then rearrange all the objects on the stack to
make room and wrap all references to those objects on both the stack and the stack.

36. Please elaborate on the following acronyms in .NET stand for IL, CIL, MSIL, CLI, and JIT?

IL or Intermediate Language is partially compiled processor-independent code. IL code is


compiled into native machine code using the current environment properties using the Just-In-
Time (JIT) compiler.

The JIT compiler translates IL code into compilation code and uses the target computer's CPU
architecture to run the .NET application. In .NET, it is called Common Intermediate Language
(CIL), and in the early days of .NET, it was called Microsoft Intermediate Language (MSIL).

CLI or Common Language Infrastructure is an open specification developed by Microsoft. It is a


compiled code library used for deployment, version control, and security. There are two types
of CLI in .NET: processing units (EXEs) and library units (DLLs).

37. Distinguish between heap and stack?

The short answer would be: the value of stacks (types inherited from [Link]) are
stored on the stack, and reference types (types inherited from [Link]) are stored on
the stack.

We can say that the stack is responsible for keeping track of what is actually being done and
where each thread is executing (each thread has its own stack). The stack, on the other hand, is
responsible for tracking more specific data or objects.

38. Please elaborate on inheritance and why we use it?

Inheritance is one of the strong concepts of object-oriented programming which collectively


transforms encapsulation into polymorphism. Through inheritance, developers can create new
classes that reuse, develop, and modify behaviors defined in other classes. This allows code
reuse in acceleration or development. Inheritance allows developers to write and debug a
single class once and reuse the same code as the basis for new classes. The class whose
members are inherited is called the base class, and the class that inherits these members is
called the derived class. By default, all classes can be inherited in .NET.

39. Distinguish between an Interface and an Abstract Class?

An interface simply explains a contract or behavior that implementing classes must-have. You
can only declare properties, methods, and events without access modifiers. All specified
members must be implemented.

An abstract class provides a partial implementation of a function and some abstract/virtual


members to be implemented by inherited entities. You can also declare fields.

40. Differentiate between [Link]() and


[Link]()?

The Clone() method returns a new array object (a small copy) that contains all of the elements
of the original array. CopyTo() method copies all the elements into another array that is already
existing. A low copy means that the content (each element in the array) contains references to
the same object as the elements in the original array. A full copy (which neither of these
methods does) creates a new instance of the object for each item, resulting in a different but
identical object.

41. Differentiate between “is” and “as” operator?

"Is" operator: In the C # language, we use the " is" operator to control the
object type. If the two objects are of the same type, it is returned true and
false otherwise.

operator "as": The operator "as" behaves like the operator "is". The only
difference is that it returns the object if they both support that type,
otherwise it returns null.

42. Differentiate between Equality Operator (==) and


Equals () Method?
The == Operator and Equals() methods are used to compare two data
elements of type value or data elements of type reference. == is the
comparison operator and the Equals() method compares the contents of a
string

43. Elaborate the indexer?

Indexing allows classes to be used in a more intuitive way. C # introduces a


new concept called indexing, which is used to treat an object like an array.
Indexers are commonly referred to as smart arrays in C #. They are not an
integral part of object-oriented programming.

44. Differentiate through exception and through


clause?

The fundamental difference is that the Throw exception decomposes, making


it difficult to find the original line number of the code that caused the
exception. Throw basically keeps track of the stack information and appends
it to the stack information unless it is started.

45. Can we use multiple catch block execution?

We can use multiple catch blocks on each attempt, but when the debugger
throws exceptions, all the catches match that type of exception with its
signature and catch the exception for each catch block, which means we can
have several catch blocks but only execute immediately.

46. Explain the usage of the extension method?

An extension method is a static method in a static class where the modifier


"this" is applied to the first parameter. The type of the first parameter is the
extended type.

47. Can we inherit private class members to the


derived class?
Yes, the private members are also inherited in the derived class, but we can't
access them. Attempts to access a private base class member in the derived
class report a compile-time error.

48. Elaborate enum?

An enum is a type of value with a set of associated named constants, often


called a list of counters. The keyword enum is used to declare a count. This is
a primitive custom data type. An enum can be an integer ( float, int, byte,
double, etc.).

49. Explain Get and Set in properties?

Get and set parts or blocks of a property are called accessors. These are
useful for limiting the availability of a property, the set accessor specifies
that we can assign a value to a private field in property and without
the set access property it is like a read-only field. Through get accessor we
can access the value of the private field, in other words, it returns a single
value. A get accessor indicates that we can publicly access the value of a
field.

We have the three types of properties

 Reading, writing.
 Read-only.
 Writing only

50. Elaborate deadlock?

A deadlock is a situation in which one process cannot complete its execution


because two or more processes are waiting for the other to complete. This
usually happens on multiple threads

Q: What is the oops concept in C#?


A: Object-Oriented Programming (OOPs) is the programming paradigm
that is defined by using objects. The objects can be considered as
examples of real-world entities such as classes that have characteristics
as well as behaviors.

Q: What is a collection in C#?

A: Collections in C# are specific classes for storing data and retrieval.


These classes help in supporting queues, stacks, lists, and hash tables.
The majority of the collection classes incorporate the same interfaces.
These classes also help in creating collections of objects of the object
classes, which is happen to be the basic class for all types of data in C#.

Q: What is the future of C#?

A: C# can be used for building Windows applications as well as creating


applications that target Linux, iOS, MacOS, and Android operating
systems. C# is one of the programming languages that is evolving quickly.
Therefore, it can be said that the future of C# is bright.

Q: What is the type safety in C#?

A: Type safety in C# was introduced to stop the object of one type from
peeking into the memory which was assigned for other objects. Safe code
is also written to stop losing data during the conversion of one type to the
other.

Q: What is a private constructor in C#?

A: A private constructor in C# is an instance constructor of a specific type.


It is mostly used in classes that comprise only static members. If a class
has more than one private constructor and zero public constructors, other
classes cannot come up with examples of this class.

Q: What is namespace in C# interview questions?

A: The namespace is a keyword that is used for declaring a scope that comprises a set of
related objects. A namespace can be used for organizing the program.

Q: Why do we use a private constructor?


A: A private constructor is used for putting a stop to creating instances of classes, mainly when
there are instance fields or even methods, like the Math class or when a method is called for
getting an instance of classes. It is majorly used for creating a singleton class. It also helps in
stopping creating an instance of a class.

1. What is the difference between Public, Static, void?


 Static: When using Static, the object is not required to access static
members.
 Public: This keyword specifies that the method of the class can be accessible
publicly
 Void: This keyword specifies that the method does not have a return type

2. What is C# also mention some features of C#.

C # is the best language for writing Microsoft .NET applications. C # gives


rapid application development in Visual Basic the power of C ++. The syntax
is similar to C ++ syntax and meets 100% OOP requirements as follows:

 Abstraction
 Encapsulation
 Polymorphism
 Inheritance

3. Please elaborate on the reason why we use C#

Choosing C # as your first programming language helps you understand


many concepts quite easily. Setting up a Hello project is very intuitive. As
one of the most popular programming languages, you have a number of
documents on the internet that can help you troubleshoot and correct errors
in your code.

One of the main selling points for .NET (C #) is that Microsoft provides a wide
range of powerful tools that can help programmers develop better
applications. By far the most important of all these tools in Visual Studio.
Visual Studio is a very powerful and rich integrated development
environment (IDE) that provides a large number of tools to support
application development.

Through C# we can develop a number of applications like


 Desktop applications
 Web applications
 Mobile applications
 Games

4. What are the advantages of C#?


 Simple and fast
 High scalability
 Cross-platform
 No buffering

5. What are the different types of comments in C#?


 Single line comment denoted with //
 Multiline comments denoted with /*
 XML comment denoted by ///

6. Elaborate the code compilation process in C#?

These steps involved in the C# compilation process

 Clubbing newly created code


 Executing assembly
 CLR

7. List down the available access modifier in the C#?


 Public
 Private
 Protected
 Internal
 Protected internal

8. Mention the different IDE’s provided by Microsoft?


 Visual Studio
 Visual web developer

9. Distinguish between continue and break statement?

Using break, you can jump over the block of code while using continue you
can jump over the iteration and continue the execution
10. What are the different approaches to pass the
parameter to a function?
 Value type parameter
 Reference type parameter
 Output parameter

12. What is managed and unmanaged code?

Managed Code is code generated by the .NET compiler. It does not depend
on the target computer as it is performed by CLR (Common Language
Runtime) and not the operating system itself. The CLR and admin code do
not provide many benefits to developers, such as waste collection, type
checking, and exemption management.

On the other hand, the Unmanaged Code is compiled directly with the
built-in machine code and depends on the architecture of the target
machine. It is executed directly by the operating system. For unmanaged
code, the developer must consider memory usage and allocation (mainly due
to memory leakage), type protection, and manual exceptions. In .NET, Visual
Basic, and the C # compiler create managed code. To get unmanaged code,
the application must be written in C or C ++.

13. Differentiate between class and object?

A class is a description of an object and what a class representation is an


object. We can think of the class as a model for the object: it describes all
the properties, methods, states, and behaviors that the implementing object
will have.

An object is an instance of a class, and a class does not become an object


until an instance is created. There can be multiple instances of objects based
on a class, each with different properties.

14. What is an abstract class?

An abstract class cannot be instantiated. It only allows other classes to


inherit from it, but cannot be instantiated. The advantage is that it uses
certain hierarchies for all subclasses. Basically, it is a type of contract that
forces all subclasses to maintain the same hierarchies or standards.

15. What is a sealed class?

Sealed classes are used to limit the inheritance function of object-oriented


programming. When a class is defined as a sealed class, the class cannot be
inherited. Visual Basic .NET uses the non-transferable keyword to seal. If a
class is derived from a sealed class, the compiler returns an error.

16. Elaborate the fundamentals of oop?


 Inheritance
 Abstraction
 Polymorphism
 Encapsulation

17. How can we inherit one class from another class?

The colon (:) is used as an inheritance operator in the C#. place the colon
and class name

18. What is method overloading?

Create the number of methods with the same name and type and class but
with different parameters is known as method overloading.

19. Differentiate between method overloading and


overriding?

Method overload

 Create the number of methods with the same name and class but with
different parameters
 It is performed within class
 The parameter must be the same

Method overriding

 If the definition of the derived class change method behavior should be


changed
 Occurs in two classes
 A parameter must be different

20. Define an interface?

Like a class, Interface can have methods, properties, events, and indexers as
members. But the interfaces only contain the membership statement. The
implementation of the interface members is given by the class that implicitly
or explicitly implements the interface.

21. Distinguish between class and struct?

Class Structure

Classes are a kind of reference value type

All reference types are arranged in a smaller memory stack memory used to assign the

The class has unlimited functionality Struct has limited functionality.

commonly used in large programs Used in the small program

Classes can be constructive or destructive A structure does not have a cons

22. Differentiate between virtual and abstract


method?

Virtual:

 It must have a default implementation


 It is overridden by the keyword override
 The virtual method has code

Abstract:

 It does not have any implementation


 It forces the derived class to override the method
 They don’t have actual code in them.

23. Illustrate the namespace in C#?


A namespace is a collection of classes and another namespace. We are using
the namespace to organize our project.

24. Define the 'using' statement?

Basically, with this keyword, we add a different namespace to our project.


For the usage for their classes. In the case of C#, the System namespace is
where many useful things are described. One of these useful things given C#
is that the Console class can let me write things that can appear on the
screen ahead of the user to this as Console I even have to inform the
compiler I'm using the System namespace. The means that if I ask
something by a specific name the compiler will look in the System to
ascertain if there's anything matching that name

25. Define boxing and unboxing?

Converting the value type into a reference type is known as boxing. While
explicit conversion of the same type is known as unboxing

26. What is an array?

An array is used to store the multiple variables of the same data type. The
array always starts from the zero indexes. Each index in the array holds a
value.

<data type> [] <identifier> = new <data type>[<size of array>];

27. What is a jagged array?

A jagged array reference to an array of array. It is a nested array whose


elements are the arrays. The element can be of different size dimensions.

28. Distinguish between array and array list?

Array:

 Use the vector array for storing the element


 The size of the array must be defined
 Typecasting is not necessary

Array List:

 Used linked list to store the element


 There is no need to specify the size
 Typecasting is necessary

29. What is collection?

The collection is work as the container for the instance of the other classes
every class implement collection interface

30. Illustrate the serialization?

It is a process that involves the conversion of one code of block into its
binary format.

31. What is parsing?

Conversion of string into to other datatypes is known as parsing for example

String a = “123”;

Int data = [Link](a);

32. Explain about delegate?

A delegated object contains a reference to a method. Delegates in C # are


the same as function markers in C or C ++. A delegated object is a reference
type variable that is used to contain a reference to a method. The reference
can be changed by runtime owned by a delegated object, a delegated object
can contain many reference functions, also known as call list, which refers to
functions in a FIFO sequence, we can refer to new functions in this list at
runtime of += operator and can be deleted by -= operator.

33. Distinguish between string and StringBuilder?


String:

 It is immutable
 Cannot perform a variety of operations.

StringBuilder:

 It is mutable.
 Support variety of operations on string builder.
 The new memory is not allocated.

34. What is LINQ?

LINQ is an acronym for Language Built-in Query and was introduced with
Visual Studio 2008. LINQ is a set of functions that extends query functions to
the syntax of the .NET language by adding sets of new standard query
operators that allow data manipulation, independently of the data source.
Supported data sources are .NET Framework collections, SQL Server
databases, [Link] datasets, XML documents, and any object collection
that supports IEnumerable or the generic IEnumerable interface <T> in both
C # and Visual Basic. In short, LINQ bridges the gap between the object
world and the data world.

35. What is garbage collection?

Garbage collection is a low-priority process that acts as an automated


memory manager that manages the allocation and release of memory to
applications. Each time a new object is created, the common language
execution allocates memory time to that object from the managed stack. As
long as free memory space is available on the managed stack, the runtime
continues to allocate space for new objects. However, memory is not infinite,
and when an application fills the memory space in the heap, garbage
collection kicks in to free up memory. When the garbage collector performs a
collection, it searches for objects in the managed stack that are no longer in
use by the application and takes the necessary steps to restore memory.
Garbage collection stops all running threads, finds any objects on the stack
that cannot be accessed by the main program and deletes them. Then
rearrange all the objects on the stack to make room and wrap all references
to those objects on both the stack and the stack.

36. Please elaborate on the following acronyms


in .NET stand for IL, CIL, MSIL, CLI, and JIT?

IL or Intermediate Language is partially compiled processor-independent


code. IL code is compiled into native machine code using the current
environment properties using the Just-In-Time (JIT) compiler.

The JIT compiler translates IL code into compilation code and uses the target
computer's CPU architecture to run the .NET application. In .NET, it is called
Common Intermediate Language (CIL), and in the early days of .NET, it was
called Microsoft Intermediate Language (MSIL).

CLI or Common Language Infrastructure is an open specification


developed by Microsoft. It is a compiled code library used for deployment,
version control, and security. There are two types of CLI in .NET: processing
units (EXEs) and library units (DLLs).

37. Distinguish between heap and stack?

The short answer would be: the value of stacks (types inherited
from [Link]) are stored on the stack, and reference types (types
inherited from [Link]) are stored on the stack.

We can say that the stack is responsible for keeping track of what is actually
being done and where each thread is executing (each thread has its own
stack). The stack, on the other hand, is responsible for tracking more specific
data or objects.

38. Please elaborate on inheritance and why we use


it?

Inheritance is one of the strong concepts of object-oriented programming


which collectively transforms encapsulation into polymorphism. Through
inheritance, developers can create new classes that reuse, develop, and
modify behaviors defined in other classes. This allows code reuse in
acceleration or development. Inheritance allows developers to write and
debug a single class once and reuse the same code as the basis for new
classes. The class whose members are inherited is called the base class, and
the class that inherits these members is called the derived class. By default,
all classes can be inherited in .NET.

39. Distinguish between an Interface and an Abstract


Class?

An interface simply explains a contract or behavior that implementing


classes must-have. You can only declare properties, methods, and events
without access modifiers. All specified members must be implemented.

An abstract class provides a partial implementation of a function and some


abstract/virtual members to be implemented by inherited entities. You can
also declare fields.

40. Differentiate between [Link]() and


[Link]()?

The Clone() method returns a new array object (a small copy) that contains
all of the elements of the original array. CopyTo() method copies all the
elements into another array that is already existing. A low copy means that
the content (each element in the array) contains references to the same
object as the elements in the original array. A full copy (which neither of
these methods does) creates a new instance of the object for each item,
resulting in a different but identical object.

41. Differentiate between “is” and “as” operator?

"Is" operator: In the C # language, we use the " is" operator to control the
object type. If the two objects are of the same type, it is returned true and
false otherwise.

operator "as": The operator "as" behaves like the operator "is". The only
difference is that it returns the object if they both support that type,
otherwise it returns null.
42. Differentiate between Equality Operator (==) and
Equals () Method?

The == Operator and Equals() methods are used to compare two data
elements of type value or data elements of type reference. == is the
comparison operator and the Equals() method compares the contents of a
string

43. Elaborate the indexer?

Indexing allows classes to be used in a more intuitive way. C # introduces a


new concept called indexing, which is used to treat an object like an array.
Indexers are commonly referred to as smart arrays in C #. They are not an
integral part of object-oriented programming.

44. Differentiate through exception and through


clause?

The fundamental difference is that the Throw exception decomposes, making


it difficult to find the original line number of the code that caused the
exception. Throw basically keeps track of the stack information and appends
it to the stack information unless it is started.

45. Can we use multiple catch block execution?

We can use multiple catch blocks on each attempt, but when the debugger
throws exceptions, all the catches match that type of exception with its
signature and catch the exception for each catch block, which means we can
have several catch blocks but only execute immediately.

46. Explain the usage of the extension method?

An extension method is a static method in a static class where the modifier


"this" is applied to the first parameter. The type of the first parameter is the
extended type.
47. Can we inherit private class members to the
derived class?

Yes, the private members are also inherited in the derived class, but we can't
access them. Attempts to access a private base class member in the derived
class report a compile-time error.

48. Elaborate enum?

An enum is a type of value with a set of associated named constants, often


called a list of counters. The keyword enum is used to declare a count. This is
a primitive custom data type. An enum can be an integer ( float, int, byte,
double, etc.).

49. Explain Get and Set in properties?

Get and set parts or blocks of a property are called accessors. These are
useful for limiting the availability of a property, the set accessor specifies
that we can assign a value to a private field in property and without
the set access property it is like a read-only field. Through get accessor we
can access the value of the private field, in other words, it returns a single
value. A get accessor indicates that we can publicly access the value of a
field.

We have the three types of properties

 Reading, writing.
 Read-only.
 Writing only

50. Elaborate deadlock?

A deadlock is a situation in which one process cannot complete its execution


because two or more processes are waiting for the other to complete. This
usually happens on multiple threads

1 new message ([Link])


1. What is a class?
A class is a template to create an object. It contains properties as well as
methods. We can create many instances of objects from a single class.

Below is an example of a class.

1 public class Student

2{

3 //data members

4 public int rollNumber { get; set; }

5 public string fullName { get; set; }

7 //method

8 public void PrintDetails()

9 {

1 //code of method
0
}
1
1}

1
2

2. What are the main concepts of


object-oriented programming?
Encapsulation, abstraction, polymorphism, and inheritance are the
main concepts of object-oriented programming.

3. Explain Encapsulation
Encapsulation is a process of wrapping function and data members
together in a class. It is like a capsule, a single unit.

Encapsulation is to prevent the unauthorized or unwanted change of data


from outside of the function.

Below is an example of encapsulation.

1 class User

2 {

3 string address;

4 private string name;

5 public string Address

6 {

7 get

8 {

9 return address;

1 }
0
set
1
1 {

1 address = value;
2
}
1
}
3
public string Name
1
4 {
1 get
5
{
1
6 return name;

1 }
7
set
1
{
8
name = value;
1
9 }

2 }
0
}
2
1 class MyProgram

2 {
2
static void Main(string[] args)
2
{
3
User u = new User();
2
4 // set accessor will invoke
2 [Link] = "Denis";
5
// set accessor will invoke
2
6 [Link] = "Germany";

2 // get accessor will invoke


7
[Link]("Name: " + [Link]);
2
// get accessor will invoke
8
[Link]("Location: " + [Link]);
2
9 [Link]("\nPress Enter Key");
3 [Link]();
0
}
3
1 }

3
2

3
3

3
4

3
5

3
6

3
7

3
8

3
9

4
0

4
1

4
2

4
3

4
4

4. What is abstraction?
Abstraction is the method of exposing only the required features of the
class and hiding unnecessary information.

START YOUR DEVELOPER CAREER


TODAY
WITH OUR C# CAREER PATH MEMBERSHIP
START YOUR CAREER Let us try to understand it with the example
of a motorbike

 A rider knows the color, name, and model of the bike. Still, he does not know
the internal engine and exhaust functionality.
So abstraction focuses on providing access to do a specific functionality
without exposing how that functionality works internally.

5. What is polymorphism?
Polymorphism means the same method but different implementation.

There are two types of polymorphism.

Compile-time polymorphism – achieved by method overloading

Refer to the below example

1 public class cellphone

2{

3 //function with the same name but different parameters.

4 public void Typing()

5 {

6 [Link]("Using keypad");

7 }

8 public void Typing(bool isSmartPhone)

9 {

1 [Link]("Using qwerty keyboard");


0
}
1
1}

1
2

Run time polymorphism – achieved by method overriding

Refer to the below example


1 public class CellPhone

2 {

3 public virtual void Typing()

4 {

5 [Link]("Using keypad");

6 }

7 }

8 public class SmartPhone : CellPhone

9 {

1 //method override
0
public override void Typing()
1
1 {

1 [Link]("Typing function from child class");


2
}
1
}
3

1
4

1
5

6. What is Inheritance in C#?


When we create a class that can inherit the data members and the methods
of another class (Parent class), it is called inheritance.

The class which inherits the properties and method is called child class,
derived class or subclass.

A class from which the child class inherits its properties and methods is a
parent class or base class.

Refer to the below example.


1 using System;

3 public class A

4{

5 private int value = 1337;

6 public class B : A

7 {

8 public int GetValue()

9 {

1 return [Link];
0
}
1
1 }

1}
2
public class InheritanceExample
1
{
3
public static void Main(string[] args)
1
4 {
1 var b = new A.B();
5
[Link]([Link]());
1
6 }

1}
7

1
8

1
9

2
0

2
1

Output will be 1337, even though Class B doesn’t directly have any
value.
7. What is an object?
An object is an instance of a class through which we access the functions of
that class. We can use the “new” keyword to create an object. A class that
creates an object in memory holds information about the functions, data
members, and behavior of that class.

Refer below for the syntax of an object.

1 //Class

3 public class Employee

4 {

5 //private members

6 private string fName { get; set; }

7 private string lName { get; set; }

9 // Method (function in a class)

1 public void Display()


0
{
1
1 [Link]("Full name is {0} {1}", fName, lName);

1 }
2
public void SetName(string firstName, string lastName)
1
{
3
fName = firstName;
1
4 lName = lastName;
1 }
5
}
1
6 class Program

1 {
7
1 static void Main(string[] args)
8
{
1
9 //this is object

2 Employee employee = new Employee();


0
[Link]("John", "Grande");
2
[Link]();
1
}
2
2

2 }
3

2
4

2
5

2
6

2
7

2
8

2
9

3
0

8. What is a constructor, and


what are its different types?
A constructor is like a method with the same name as the class, but it is a
unique method. Even if it is not created, the compiler creates a default
constructor in memory at the time of creating an object of the class.

 The constructor is used to initialize the object with some default values.

 Default constructor, parameterized constructor, copy constructor, static


constructor, private constructor are different constructor types.

Refer to the below sample for different constructor types.


1 public class Student

2 {

3 private int rollNumber { get; set; }

4 private string fullName { get; set; }

6 //default constructor

7 public Student()

8 { //code goes here

9 }

1
0
//parameterized constructor
1
1 public Student(int rNum, string fName)

1 {
2
[Link] = rNum;
1
[Link] = fName;
3
}
1
4

1 //static constructor
5
static Student()
1
6 { //code goes here

1 }
7

1
//copy constructor
8
public Student(Student student)
1
9 {
2 rollNumber = [Link];
0
fullName = [Link];
2
1 }

2 }
2
2
3

2
4

2
5

2
6

2
7

2
8

2
9

9. What is a destructor in C#?


The Destructor clears out the memory to free up resources. It is managed
automatically by the garbage collector. [Link]() is called
internally for this purpose. However, if required, it can be done explicitly
using a destructor.

Refer to the below example.

1 public class Purchase

2 {

3 //Syntax to write a destructor.

4 ~Purchase()

5 {

6 //code here to release resources.

7 }

8 }
10. Is C# code managed or
unmanaged code?
C# is managed code because Common language runtime compiles the code
to Intermediate language.

11. What are value types and


reference types?
We can categorize variables into value type and reference type.

Variables of value type contain the value directly while the variable of a
reference type contains the reference of the memory address where the
value is stored actually in the memory.

For example bool, byte, int, char, and decimal are value type

And String, class, delegates are examples of reference types.

Below is the pictorial representation of the value type.


Below is the pictorial representation of the reference type.

12. What are namespaces, and is


that compulsory?
A namespace is a way of organizing classes of the same group or
functionality under the same name. We can call it a module. Although it is
not compulsory to put class in a namespace.

Refer to the syntax below.


1 namespace demoapp

2{

3 class SomeClass

4 {

5 public static void someMethod()

6 {

7 [Link]("Creating my namespace");

8 }

9 }

1}
0

13. Explain types of comments in


c# with examples.
There are three types of comments in c#.

 Single line comments


 Multiline comments
 XML comments

Example of a single-line comment

//Hey, this is a single line comment

Example of a multi line comment

/*This is a multiline comment

written in two lines

2*/

Example of an XML comment

///Summary

///Here you can write anything


///summary

14. What is an interface? Give an


example.
An interface is another form of an abstract class that has only abstract public
methods, and these methods only have the declaration and not the
definition. A class implementing the interface must have the implementation
of all the methods of the interface.

For Example

1 interface IPencil

2 {

3 void Write(string text);

4 void Sharpen(string text);

5 }

7 class Pencil : IPencil

8 {

9 public void Write(string text)

1 {
0
//some code here
1
1 }

1
2
public void Sharpen(string text)
1
{
3
//some code here
1
4 }
1 }
5
1
6

1
7

1
8

15. How to implement multiple


interfaces with the same method
name in the same class?
If we want to implement multiple interfaces with the same method name,
then we cannot directly implement the body of the function. We have to
explicitly provide the name of the interface to implement the body of the
method. In this way, the compiler decides which interface methods we are
referring to, and this resolves the issue.

Let us see the below example.

1 interface myInterface1

2 {

3 void Print();

4 }

5 interface myInterface2

6 {

7 void Print();

8 }

9 class Student : myInterface1,

1 myInterface2
0
{
1
1 void [Link]()

1 {
2
1 [Link]("For myInterface1 !!");
3
}
1
4

1 void [Link]()
5
{
1
[Link]("For myInterface2 !!");
6
}
1
7}

1
8

1
9

2
0

2
1

16. What is the virtual method,


and how is it different from the
abstract method?
A virtual method must have a default implementation, and We can override
this virtual method using the override keyword in the derived class.

The abstract method is without implementation, and it is created inside the


abstract class only. In the case of an abstract class, the class derived from
the abstract class must have an implementation of that abstract method.

Example of a virtual method.

1 public class CellPhone

2 {

3 public virtual void Typing()


4 {

5 [Link]("Using old keypad");

6 }

7 }

9 public class SmartPhone : CellPhone

1 {
0
public override void Typing()
1
1 {

1 [Link]("Using qwerty keyboard");


2
}
1
}
3

1
4

1
5

Example of an abstract method.

1 public abstract class CellPhones

2 {

3 //no default implementation

4 public abstract void Typing();

5 }

7 public class OldPhones : CellPhones

8 {

9 //function override

1 public override void Typing()


0
{
1
1 [Link]("Using keypad");

1 }
2 }

1
3
public class SmartPhones : CellPhones
1
4 {

1 //function override
5
public override void Typing()
1
{
6
[Link]("Using Qwerty keyboard");
1
7 }
1}
8

1
9

2
0

2
1

2
2

2
3

17. What is method overloading


and method overriding?
Method overloading is when we have a function with the same name but a
different signature.

Method overriding is when we override the virtual method of a base class in


the child class using the override keyword.

Both, method overloading and overriding are a type of polymorphism.

18. What is the static keyword?


We use the “static” keyword to create a static class, a static method, or
static properties.

When we create a static class, then there can be only static data members
and static methods in that class.

Static means that we cannot create the instance of that class. That class can
be used directly like [Link].

When there is a need for special functions, which are typical for all the
instances of other classes, then we use static class.

For example, there is a requirement to load some default application-level


values. We create a static class with static functions. That class is then
accessible to all other classes without creating any instance. It also shares
the same data with all the classes.

Refer to the below example.

1 public static class Setting

2 {

3 public static int fetchDefault()

4 {

5 int maxAmount = 0;

6 //code to fetch and set the value from config or some file.

7 return maxAmount;

8 }

9 }

1
0
public class Sales
1
1 {

1 //not required to create an instance.


2
int maxAmount = [Link]();
1
}
3

1
4

1
5

19. Can we use “this” with the


static class?
No, we cannot use “this” with the static class because we can only use static
variables and static methods in the static class.

20. What is the difference


between constants and read-only?
Constant variables have to be assigned a value at the time of declaration
only, and we cannot change the value of that variable throughout the
program.

We can assign the value to the read-only variable at the time of declaration
or in a constructor of the same class.

Here is an example of constants.

1 using System;

3 namespace demoapp

4{

5 class DemoClass

6 {

7 // Constant fields

8 public const int myvar = 101;

9 public const string str = "staticstring";


1 // Main method
0
static public void Main()
1
1 {

1 // Display the value of Constant fields


2
[Link]("The value of myvar: {0}", myvar);
1
[Link]("The value of str: {0}", str);
3
}
1
4 }
1}
5

1
6

1
7

1
8

Here is an example of read-only.

1 using System;

3 namespace demoapp

4{

5 class MyClass

6 {

7 // readonly variables

8 public readonly int myvar1;

9 public readonly int myvar2;

1 // Values of the readonly


0
// variables are assigned
1
1 // Using constructor

1 public MyClass(int b, int c)


2
{
1
3 myvar1 = b;

1 myvar2 = c;
4
[Link]("Display value of myvar1 {0}, " +
1
5 "and myvar2 {1}", myvar1, myvar2);

1 }
6

1
// Main method
7
static public void Main()
1
8 {
1 MyClass obj1 = new MyClass(100, 200);
9
}
2
0 }

2}
1

2
2

2
3

2
4

2
5

2
6

2
7

21. What is the difference


between string and string builder
in C#?
A string is an immutable object. When we have to do some actions to change
a string or append a new string, it clears out the old value of the string
object, and it creates a new instance in memory to hold the new value in a
string object. It uses System. String class, for example.
1 using System;

2 namespace demoapp

3{

4 class StringClass

5 {

6 public static void Main(String[] args) {

7 string val = "Hello";

8 //creates a new instance of the string

9 val += "World";

1 [Link](val);
0
}
1
1 }

1}
2

1
3

StringBuilder is a mutable object. It means that it creates a new instance


every time for the operations like adding string (append), replace string
(replace). It uses the old object only for any of the operations done to the
string and thus increases the performance. It uses [Link]
class, for example.

1 using System;

2 using [Link];

4 namespace demoapp

5{

6 class StringClass
7 {

8 public static void Main(String[] args) {

9 StringBuilder val = new StringBuilder("Hello");

1 [Link]("World");
0
[Link](val);
1
1 }

1 }
2
}
1
3

1
4

The output of both the program is the same, “Hello World.”

22. Explain the “continue” and “break” statement.

We can use continue and break statements in a loop in c#. Using a break
statement, we can break the loop execution, while using the continue
statement, we can break one iteration of the loop.

An example of the break statement.

1 using System;

2 namespace demoapp

3{

4 class LoopingStatements

5 {

6 public static void Main(String[] args)

7 {

8 for (int i = 0; i <= 5; i++)

9 {
1 if (i == 4)
0
{
1
1 break; //this will break the loop

1 }
2
[Link]("The number is " + i);
1
[Link]();
3
} //control will jump here after the break statement.
1
4 }
1 }
5
}
1
6

1
7

1
8

1
9

Here is the same example with a continue statement.

1 using System;

2 namespace demoapp

3{

5 class LoopingStatements

6 {

7 public static void Main(String[] args)

8 {

9 for (int i = 0; i <= 5; i++)

1 {
0
if (i == 4)
1
1 {

1
2 continue;// it will skip the single iteration

1 }
3
[Link]("The number is " + i);
1
4 [Link]();

1 }
5
}
1
}
6
}
1
7

1
8

1
9

2
0

23. What are boxing and unboxing?

Conversion of value type datatype to reference type (object) datatype is


called boxing.

1 For Example:

2 namespace demoapp

3{

4 class Conversion

5 {

6 public void DoSomething()

7 {

8 int i = 10;

9 object o = i;

1 }
0
}
1
1}

1
2

Unboxing is the conversion of reference type datatype to value type.

For Example:

1 namespace demoapp

2{

3 class Conversion

4 {

5 public void DoSomething()

6 {

7 object o = 222;

8 int i = (int)o;

9 }

1 }
0
}
1
1

24. What is a sealed class?

We use a “sealed” keyword to create a sealed class. Classes are created as a


sealed class when there is no need to inherit that further or when there is a
need to restrict that class from being inherited.

Refer to the syntax below:

public sealed class MyClass


{
//properties and methods
}

25. What is a partial class?


There is a feature in the C# language to divide a single class file into
multiple physical files. To achieve this, we have to use the “partial” keyword.
At compile time, it is logically one file only.

So we cannot have a method with the same name or a variable with the
same name in two different partial class files.

Here, to facilitate the developers to break down the big class files into
multiple small physical files, this feature is provided.

26. What is enum?

In C#, the “enum” keyword is used to declare an enumeration. An enum is a


value type. It is a collection of related named constants referred to as an
enumerator list.

An enum type can be any of these (int, float, double, and byte). However, to
use it beside int, explicitly casting is required.

To create a numeric constant in the .NET framework enum is used. All the
members of the enum are of enum type, and there must be a numeric value
for each enum type.

Int is the default type of the enumeration element. By default, the first
enumerator has the value 0. The value of each successive enumerator is
then increased by 1.

27. What is dependency injection, and how can it be achieved?

Dependency injection is a design pattern. Here, instead of creating an object


of a class in another class (dependent class) directly, we are passing the
object as an argument in the constructor of the dependent class. It helps to
write loosely coupled code and helps to make the code more modular and
easy to test.

There are 3 ways to achieve dependency injection.

 Constructor Injection: This is the most commonly used Injection type. In


constructor injection, we can pass the dependency into the constructor. We
have to make sure that we do not have a default constructor here, and the
only one should be a parameterized constructor.

 Property Injection: There are cases when we need the default constructor of a
class, so in that case, we can use property injection.
 Method Injection: In method injection, we need to pass the dependency in the
method only. When the entire class does not require that dependency, there
is no need to implement constructor injection. When we have a dependency
on multiple objects, then instead of passing that dependency in the
constructor, we pass that dependency in the function itself where it is
required.

28. The “using” statement.

The keyword “using” is used to define the scope of the resources used in
that using statement block. All the resources used inside the using code
block get disposed of once the code block completes execution.

class Books : IDisposable


{
private string _name { get; set; }
private decimal _price { get; set; }
public Books(string name, decimal price)
{
_name = name;
_price = price;
}
public void Print()
{
[Link]("Book name is {0} and price is {1}", _name, _price);
}
public void Dispose()
{
throw new NotImplementedException();
}
}

class Students
{
public void DoSomething()
{
using (Books myBook = new Books("book name", 12.45))
{
[Link]();
}
}
}

29. What are the access modifiers? Explain each type.

Access modifiers are keywords used to provide accessibility to a class,


member, or a function.
Below are its types

 Public: Can be accessed anywhere without any restriction


 Protected: Access is limited up to the class, which inherits this class.
 Internal: Can be accessed only within the current assembly.
 Private: Cannot be accessed outside.

Syntax of access modifier

public class Product


{
public void Print()
{
//code to print something.
}
}

30. What are delegates?

Delegates are like function pointers. It is a reference data type that holds the
reference of a method. We use delegates to write generic type-safe
functions. All delegates derive from System. Delegate.

A delegate can be declared using the delegate keyword followed by a


function signature, as shown below.

The Following are the characteristics of delegates.

 Delegates derive from the System. Delegate class.


 Delegates have a signature as well as return type. A function assigned to
delegates must be fit with this signature.
 Delegates can point to instance methods or static.
 Delegate objects, once created, can dynamically invoke the methods it points
to at runtime.
 Delegates can call methods synchronously and asynchronously.

using System;
namespace demoapp
{
class DelegateClass
{
// declare delegate
public delegate void Print(int value);
static void Main(string[] args)
{
// Print delegate points to PrintNumber
Print printDel = PrintNumber;
// or
// Print printDel = new Print(PrintNumber);
printDel(100000);
printDel(200);
// Print delegate points to PrintMoney
printDel = PrintMoney;
printDel(10000);
printDel(200);
}
public static void PrintNumber(int num)
{
[Link]("Number: {0,-12:N0}", num);
}
public static void PrintMoney(int money)
{
[Link]("Money: {0:C}", money);
}
}
}

31. What are the different types of delegates?

There are three types of delegates.

 Single Delegate: Single Delegate can invoke a single method.


 Multicast Delegate: Multicast delegates can invoke multiple methods. The
delegate method can do multicasting. We can add a method in the delegate
instance using + operator, and we can remove a method using – operator. All
the methods are invoked in sequence as they are assigned.
 Generic Delegate: .Net Framework 3.5 Introduces Generic delegates. There
is no need to create an instance in a generic delegate.

1Print printNumDel = PrintNumber;

2Print printMonDel = PrintMoney;

3// MultiCast Delegate

4Print multiPrintDel = printNumDel + printMonDel;

5multiPrintDel(100);

6multiPrintDel = printNumDel - printMonDel;


7multiPrintDel(100);

32. What is an array? Explain Single and multi-dimensional arrays.

The array stores the value of the same type. It is a collection of variable
stores into a memory location.

For example

int[] marks = new int[3] { 25, 34, 89 };

A single-dimensional array is a linear array. Single-dimensional array stores


variables in a single row. The above example is a single-dimensional Array.

Arrays can have more than one dimension. Multi-dimensional arrays are also
called rectangular Arrays.

For example

int[,] numbers = new int[3, 2] { { 1, 2 }, { 2, 3 }, { 3, 4 } };

33. What is the difference between the [Link]() and [Link]() ?

Using the Clone() method, we can create a new array object containing all
the elements of the original array and using the CopyTo() method. All the
items of existing array copies into another existing array. Both ways create a
shallow copy.

1int[] marks = new int[3] { 25, 34, 89 };<br>int[] marksCopy;<br>int[] marksClone =


(int[])[Link]();<br>[Link](marks,0);

34. What is the difference between array and arraylist?

When we want to store the items of the same type, then the array is used.
The array has a fixed size but not in the case of an arraylist. We can store
any type of data type in an array list.
Refer to the example of an array and array list.

1 using [Link];

2 namespace demoapp

3{

4 class Sample

5 {

6 //Array and Araraylist.

7 public void ArrayFunction()

8 {

9 string[] country = new string[3];

1 country[0] = "USA"; //only string value can be added


0
country[1] = "Denmark";
1
1 country[2] = "Russia";

1 //can store different data types


2
ArrayList arraylist = new ArrayList();
1
[Link](3);
3
[Link]("USA");
1
4 [Link](false);
1 }
5
}
1
6}

1
7

1
8

1
9

2
0

35. What is a jagged array in C#?


A jagged array is like a nested array; each element of a jagged array is an
array in itself. The item of a jagged array can be of different dimensions and
sizes.

A jagged array is a special type of array introduced in c#. A Jagged array is


an array of an array in which the length of each array index can differ.

Refer to the below example.

1 namespace demoapp

2{

3 public class JaggedArrayClass

4 {

5 public void ShowJaggedArray()

6 {

7 int[][] jaddedArray = new int[2][];

8 jaddedArray[0] = new int[3] { 1, 2, 3 };

9 jaddedArray[1] = new int[4] { 1, 2, 3, 4 };

1 }
0
}
1
1}

1
2

36. What is the difference between struct and class?

Class and struct are both user-defined but have a significant difference.

Struct

 A Struct inherits from System. Value type and so it is a value type.


 It is preferred to use struct when there is a small amount of data.
 A structure cannot be abstract.
 There is no need to create an object with a new keyword.
 Struct does not have permission to create any default constructor.
Syntax of struct

1struct MyStruct

2 {

3 public int MyProperty1 { get; set; }

4 public int MyProperty2 { get; set; }

5}

Class

 The class is a reference type in c#, and it inherits from the System. Object
Type.
 When there is a large amount of data, then in that scenario, classes are used.
 We can inherit one class from another class.
 A class can be an abstract type.

37. What is the difference between throw and throw ex?

“Throw” statement holds the original error stack of the previous function or
function hierarchy. In contrast,

“Throw ex” has the stack trace from the throw point.

So, it is always advised to use “Throw” because it provides exact error


information related to the function and gives you actual trace data of error
source.

38. Explain the difference between finally and finalize block?

Finally - it is a code block part of execution handling this code block executes
irrespective of whether the exception occurs or not.

Finalize – It is a method called just before garbage collection. The compiler


calls this method automatically when not called explicitly in code.

39. Explain var and dynamic.

We can declare the var type of a variable without specifying the .net data
types explicitly. The compiler automatically detects the type of a variable at
the compile-time based on the value assigned to it. We cannot declare a var
type variable without assigning a value to it. The value of the var type
variable cannot be changed later in the code.

Dynamic is the opposite of var. We can change the value of a variable of


type dynamic in the code later. It also decides the type of the variable based
on the value assigned to it.

Like at the time of creating a variable of type dynamic, a value of Integer


type is assigned to it, then also in the code further, we can assign a string
type value to that variable. It holds the last changed value and acts like the
data type of the latest values it holds.

Let us see the example to understand it in more detail.

1public class Bike

2 {

3 dynamic someValue = 21;

4 public Bike()

5 {

6 //assigned string value later

7 someValue = "Hello";

8 }

9}

In the above example, if we declare the variable “someValue ” to type var


instead of dynamic, it throws an error. The reason for that error is that in the
next line, we changed the value of the variable and assigned a string value.

40. What are Anonymous types in C#?

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

When there is a need to define read-only properties in a single object without


defining each type. In that case, we use anonymous types. Here, a compiler
generates type and is accessible only for the current block of code.
Refer to the below example.

1 public class SomeClass

2 {

3 public void print()

4 {

5 var anonymousData = new

6 {

7 FirstName = "John",

8 SurName = "lastname"

9 };

1 [Link]("First Name : " + [Link]);


0
}
1
1}

1
2

41. What is multithreading, and what are its different states?

Any code block in c# runs in a process called a thread, and it is the


execution path of the program. Usually, an application runs in a single
thread. But multithreading helps to run the application in multiple threads.
Using multithreading, we can divide the execution of our process among
different threads to execute it simultaneously.

In multithreading, we can create multiple threads and assign particular tasks


or put a code block to get executed. In this way, we can run more than one
task at a time. This code block executes simultaneously and can save time,
and in this way, we can make programs more efficient and fast.

Thread has its lifecycle, which includes various states of thread.

Aborted 256 The thread state includes AbortRequested and the thread is now dead, but its sta
changed to Stopped.

The Abort(Object) method has been invoked on the thread, but the thread has no
AbortRequested 128
received the pending ThreadAbortException that will attempt to terminate it.

The thread is being executed as a background thread, as opposed to a foreground


Background 4
state is controlled by setting the IsBackground property.

Running 0 The thread has been started and not yet stopped.

Stopped 16 The thread has stopped.

StopRequested 1 The thread is being requested to stop. This is for internal use only.

Suspended 64 The thread has been suspended.

SuspendRequested 2 The thread is being requested to suspend.

Unstarted 8 The Start() method has not been invoked on the thread.

The thread is blocked. This could be the result of calling Sleep(Int32) or Join(), of r
WaitSleepJoin 32 lock – for example, by calling Enter(Object) or Wait(Object, Int32, Boolean) – or o
thread synchronization object such as ManualResetEvent.

Source: [Link]
redirectedfrom=MSDN&view=netcore-3.1

42. How is exception handling done in C#?

Try, catch, finally, and throw. These are the keywords used to handle the
exception.

Below is the explanation of each keyword.

 Try: We keep the code in the try block for which we want to handle the
exception.
 Catch: When any exception occurs in a try block, then it is caught in a catch
block with the help of an exception handler.
 Finally: To execute a code block irrespective of error, we place that code in
the finally block to get executed.
 Throw: Throws an exception when an issue occurs.

Below is the example of exception handling.

1 public class SomeClass

2 {

3 public void GetData()

4 {

5 try

6 {

7 //write some code here

8 }

9 catch (Exception)

1 {
0
throw;
1
1 }

1 finally
2
{
1
/*code to execute in the last
3
like dispose objects and resource*/
1
4 }
1 }
5
}
1
6

1
7

1
8

1
9

43. What are the custom exceptions?

Sometimes some errors need to be caught as per user requirements. Custom


exceptions are used for them and are user-defined exceptions.

Refer to the below example.

1 public class Purchase

2{

3 public void DoPurchase(int quantity)

4 {

5 if (quantity == 0)

6 {

7 //this will throw error here with the custom message

8 throw new Exception("Quantity cannot be zero");

9 }

1 }
0
}
1
1

44. What is LINQ in C#?

Language integrated query is the full form of LINQ. It is a method of querying


data using the .net capabilities and c# syntax similar to SQL query.

The advantage of LINQ is that we can query different sources of data. The
data source could be either collection of objects, XML files, JSON files, In-
memory data or lists or, database objects. We can easily retrieve data from
any object that implements the IEnumerable<T> interface.

Below is the syntax of LINQ


1 public class Devices
2
3 {
4 public void GetData()
5 {
6 List<string> mobiles = new List<string>() {
7 "Iphone","Samsung","Nokia","MI"
8 };
9 //linq syntax
1 var result = from s in mobiles
0
where [Link]("Nokia")
1
select s;
1
}
1
2}
1
3

45. What is serialization?

When we want to send an object through a network, then we have to convert


that object into a stream of bytes. Serialization is a process of converting an
object into a stream of bytes. To facilitate the object for serializable, it should
implement ISerialize Interface. The process of De-serialization is the reverse
process of creating an object from a stream of bytes.

46. What are generics in c#?

Generics increase performance, increase type safety, reduce repeated code,


and makes reusable code. Using generics, we can create collection classes. It
is preferred to use [Link] namespace instead of classes
such as ArrayList in the [Link] namespace to create a generic
collection.

Generics encourages the usage of parameterized types. Refer to the


example below

1 using System;
2
3
4 namespace demoapp
5 {
6 //We use < > to specify Parameter type
7 public class GFG<T>
8 {
9 //private data members
10 private T data;
11 //using properties
12 public T value
13 {
14 /using accessors
15 get
16 {
17 return [Link];
18 }
19 set
20 {
21 [Link] = value;
22 }
23 }
24 }
25 //vehicle class
26 class Vehicle
27 {
28 //Main method
29 static void Main(string[] args)
30 {
31 //instance of string type
32 GFG<string> company = new GFG<string>();
33 [Link] = "Tata motors";
34 //instance of float type
35 GFG<float> version = new GFG<float>();
36 [Link] = 6.0F;
37 //display Tata motors
38 [Link]([Link]);
39 //display 6
40 [Link]([Link]);
41 }
42 }
}

47. What is reflection?

Reflection is when managed code can read its own metadata to find
assemblies.

“Reflection provides objects (of type Type) that describe assemblies,


modules, and types. You can use reflection to dynamically create an instance
of a type, bind the type to an existing object, or get the type from an existing
object and invoke its methods or access its fields and properties. If you are
using attributes in your code, reflection enables you to access them. For
more information, see Attributes.”

Source: [Link]
guide/concepts/reflection

The following information can be retrieved using reflection.

 Assembly name
 Class name
 Method name
 Object type
 It Identifies properties and methods.
48. How to use nullable types?

In c#, we can also assign a null value to the variable. Such types are called
nullable types.

Example below:

namespace demoapp
{
class Calculate
{
int? number = null;
public Calculate(int num)
{
number = num;
}
public void DoCalculation()
{
if ([Link])
{
//do something
}
}
}
}

49. Which is the parent class of all classes which we create in C#?

[Link].

50. Explain code compilation in C#

Below are the steps explaining the code compilation.

 The C# compiler compiles the code into managed code, also called Byte
code.
 Then JIT (Just in time compiler) compiles the Byte code into Native or machine
language, which is directly executed by CPU.

You might also like