C# Interview Questions
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.
- 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.
It contains both declaration and definition parts. It contains only a declaration part.
It contains a constructor.
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.
A class can only use one abstract class. A class can use multiple interfaces.
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
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#
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
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#?
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.
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#
26. What is the difference between to dispose and finalize methods 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#
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
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#
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.
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#
Because private virtual methods are not accessible outside the class.
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.
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.
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.
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.
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#
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- 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.
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;
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;
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.
Let’s move ahead in C# Interview Questions and see the next category.
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.
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.
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
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
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:
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.
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’.
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
Ans- Colon is used as an inheritance operator in C#. Place the colon and the class name.
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.
Ans- Streamreader and StreamWriter are classes of [Link]. Used when we want
to read or write charact90, Reader based data, respectively.
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.
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.
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.
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.
n – newline character
b – backspace
– backlash
‘ – Single quote
” – Double quote
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:
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:
To know more about arrays in Java, Python , and C++ you can go through
the following blogs:
Python array
Java array
C++ array
Example:
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
To know more about Interface in Java, check out the following blog:
Java Interface
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.
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
Example:
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.
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.
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,
Ans- C# consists of [Link] namespace which has classes that compute and perform various
operations on files like creating, deleting, opening
and closing etc.
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.
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
Example:
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.
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:
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.
Example:
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.
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.
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace DemoApplication
{
interface Guru99Interface
{
void SetTutorial(int pID, string pName);
String GetTutorial();
}
[Link](1,".Net by Guru99");
[Link]([Link]());
[Link]();
}
}
}
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.
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.
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);
}
}
}
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.
23. How can we sort the elements of the Array in descending order?
Using Sort() methods followed by Reverse() method.
Eg:
try {
GetAllData();
}
catch (Exception ex) {
}
In the above example, we can omit the parameter from catch statement.
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.
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.
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.
namespace DemoApplication
{
class Program
{
static void Main(string[] args)
{
Queue qt = new Queue();
[Link](1);
[Link](2);
[Link](3);
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
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:
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.
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++.
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.
Ex.
Abstract class:
Interface:
C# ref keywords pass arguments by reference and not value. To use the
‘ref’ keyword, you need to explicitly mention ‘ref’.
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.
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
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:
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)
{
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 {
// Creating ArrayList
ArrayList My_features= new ArrayList();
// Parent class 2
class Scaler2 :Scaler{
// Creating ArrayList
ArrayList My_features = new ArrayList();
// Child class
class ScalertoScaler : Scaler2 {
}
// Main method
static public void Main()
{
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.
Unboxing: Unboxing converts reference type (object) to value type (int, char, etc.) using an
explicit conversion process.
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.
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.
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.
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#
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.
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
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.
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().
Assembly
Module
Enum
MethodInfo
ConstructorInfo
MemberInfo
ParameterInfo
Type
FieldInfo
EventInfo
PropertyInfo
For ex:
class IB {
// Constant fields
public const int xvar = 20;
public const string str = "InterviewBit";
// Main method
static public void Main()
{
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:
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.
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.
C# Coding Problems
23. Write a program in C# Sharp to reverse a string?
internal static void ReverseString(string str)
{
Output:
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.
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.
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#.
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.
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.
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.
To know more about C# 8.0 new features visit What's new in C# 8.0
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.
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]();
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
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.
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.
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
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#.
To know more about C# 7.0 new features visit What's new in C# 7.3
22. What will be the output here? or will it throw any error?
{
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#?
25. What is IDisposable Interface in C#? How to implement the dispose method?
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;
}
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.
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#.
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#?
39. Explain the concept of Parallel Processing, Concurrency, and Async Programming in .NET?
For more visit Parallel Processing, Concurrency, and Async Programming 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#.
C# 6.0 has many new features. For more visit What's new in C# 6.0
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);
}
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.
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: ?: , => , & , && , *
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.
arr2D[0,0] = 1;
A: An array, with elements consisting of arrays of different sizes and dimensions, is called a
jagged array.
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.
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.
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.
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.
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?
Abstraction
Encapsulation
Polymorphism
Inheritance
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.
Desktop applications
Web applications
Mobile applications
Games
Using break, you can jump over the block of code while using continue you
can jump over the iteration and continue the execution
Finally block called after the execution of try catch block while finalize
called just before the garbage collection
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 ++.
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.
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.
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.
Inheritance
Abstraction
Polymorphism
Encapsulation
The colon (:) is used as an inheritance operator in the C#. place the colon and class name
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
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.
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
Abstract:
Converting the value type into a reference type is known as boxing. While
explicit conversion of the same type is known as unboxing
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>];
Array:
Array List:
The collection is work as the container for the instance of the other classes
every class implement collection interface
It is a process that involves the conversion of one code of block into its
binary format.
String a = “123”;
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.
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.
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.
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?
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).
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.
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.
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.
"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.
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.
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.
Reading, writing.
Read-only.
Writing only
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.
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.
Abstraction
Encapsulation
Polymorphism
Inheritance
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.
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
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 ++.
The colon (:) is used as an inheritance operator in the C#. place the colon
and class name
Create the number of methods with the same name and type and class but
with different parameters is known as method overloading.
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
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.
Class Structure
All reference types are arranged in a smaller memory stack memory used to assign the
Virtual:
Abstract:
Converting the value type into a reference type is known as boxing. While
explicit conversion of the same type is known as unboxing
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.
Array:
Array List:
The collection is work as the container for the instance of the other classes
every class implement collection interface
It is a process that involves the conversion of one code of block into its
binary format.
String a = “123”;
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.
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.
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).
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.
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.
"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
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.
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.
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.
Reading, writing.
Read-only.
Writing only
2{
3 //data members
7 //method
9 {
1 //code of method
0
}
1
1}
1
2
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.
1 class User
2 {
3 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";
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.
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.
2{
5 {
6 [Link]("Using keypad");
7 }
9 {
1
2
2 {
4 {
5 [Link]("Using keypad");
6 }
7 }
9 {
1 //method override
0
public override void Typing()
1
1 {
1
4
1
5
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.
3 public class A
4{
6 public class B : A
7 {
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.
1 //Class
4 {
5 //private members
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 }
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
The constructor is used to initialize the object with some default values.
2 {
6 //default constructor
7 public Student()
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
2 {
4 ~Purchase()
5 {
7 }
8 }
10. Is C# code managed or
unmanaged code?
C# is managed code because Common language runtime compiles the code
to Intermediate language.
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
2{
3 class SomeClass
4 {
6 {
7 [Link]("Creating my namespace");
8 }
9 }
1}
0
2*/
///Summary
For Example
1 interface IPencil
2 {
5 }
8 {
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
1 interface myInterface1
2 {
3 void Print();
4 }
5 interface myInterface2
6 {
7 void Print();
8 }
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
2 {
6 }
7 }
1 {
0
public override void Typing()
1
1 {
1
4
1
5
2 {
5 }
8 {
9 //function override
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
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.
2 {
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
4
1
5
We can assign the value to the read-only variable at the time of declaration
or in a constructor of the same class.
1 using System;
3 namespace demoapp
4{
5 class DemoClass
6 {
7 // Constant fields
1
6
1
7
1
8
1 using System;
3 namespace demoapp
4{
5 class MyClass
6 {
7 // readonly variables
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
2 namespace demoapp
3{
4 class StringClass
5 {
9 val += "World";
1 [Link](val);
0
}
1
1 }
1}
2
1
3
1 using System;
2 using [Link];
4 namespace demoapp
5{
6 class StringClass
7 {
1 [Link]("World");
0
[Link](val);
1
1 }
1 }
2
}
1
3
1
4
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.
1 using System;
2 namespace demoapp
3{
4 class LoopingStatements
5 {
7 {
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
1 using System;
2 namespace demoapp
3{
5 class LoopingStatements
6 {
8 {
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
1 For Example:
2 namespace demoapp
3{
4 class Conversion
5 {
7 {
8 int i = 10;
9 object o = i;
1 }
0
}
1
1}
1
2
For Example:
1 namespace demoapp
2{
3 class Conversion
4 {
6 {
7 object o = 222;
8 int i = (int)o;
9 }
1 }
0
}
1
1
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.
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.
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.
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 Students
{
public void DoSomething()
{
using (Books myBook = new Books("book name", 12.45))
{
[Link]();
}
}
}
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.
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);
}
}
}
5multiPrintDel(100);
The array stores the value of the same type. It is a collection of variable
stores into a memory location.
For example
Arrays can have more than one dimension. Multi-dimensional arrays are also
called rectangular Arrays.
For example
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.
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 {
8 {
1
7
1
8
1
9
2
0
1 namespace demoapp
2{
4 {
6 {
1 }
0
}
1
1}
1
2
Class and struct are both user-defined but have a significant difference.
Struct
1struct MyStruct
2 {
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.
“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.
Finally - it is a code block part of execution handling this code block executes
irrespective of whether the exception occurs or not.
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.
2 {
4 public Bike()
5 {
7 someValue = "Hello";
8 }
9}
2 {
4 {
6 {
7 FirstName = "John",
8 SurName = "lastname"
9 };
1
2
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.
Running 0 The thread has been started and not yet stopped.
StopRequested 1 The thread is being requested to stop. This is for internal use only.
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
Try, catch, finally, and throw. These are the keywords used to handle the
exception.
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.
2 {
4 {
5 try
6 {
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
2{
4 {
5 if (quantity == 0)
6 {
9 }
1 }
0
}
1
1
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.
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 }
}
Reflection is when managed code can read its own metadata to find
assemblies.
Source: [Link]
guide/concepts/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].
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.