Interview Questions
Interview Questions
C#:
1- What are the differences between "continue" and "break" statements in C#?
Ans:
class itisas
{
static void Main(string[] args)
{
object[] MyObjects = new object[4];
MyObjects[0] = new Student();
MyObjects[1] = new Teacher();
MyObjects[2] = "Student";
MyObjects[3] = "Teacher";
for(int i = 0; i < 4; i++)
{
string s = MyObjects[i] as string;
[Link]($"Inspecting element: {MyObjects[i]}");
if (s == null)
{ [Link](" ->> Incompatible type"); }
else
{ [Link](" ->> Compatible type"); }
[Link](", with string!");
}
[Link](); ;
}
Output:
3- What are the differences between arrays, list, collection and hashtable?
Ans:
Lists allow duplicate items, can be accessed by index, and support linear
traversal:
Array ArrayList
An Array is strongly-typed. We ArrayList is a non-generic collection type.
can store only the same type of ArrayList's internal Array is of the object type. So,
data. we can store multiple types of data in ArrayList.
ArrayList is dynamic in term of capacity. If the
Array stores a fixed number of
number of element exceeds, ArrayList will
elements.
increase to double its current size.
If we are using a large number of ArrayList then it
Array provides better
degrades performance because of boxing and
performance than ArrayList.
unboxing.
Array uses static helper class ArrayList implements an IList interface so, it
Array which belongs to system provides a method that we can use for easy
namespace implementation.
Array belongs to namespace ArrayList belongs to namespace
System [Link]
The Array cannot accept null. An Array can accept null.
Example:string[] array1=new Example:ArrayList a1=new
string[5];array1[0]=”Hello”;array1[ ArryList();[Link](null);[Link](1,”hi”);[Link](3);a
1]=”Bye”; [Link](8.23);
*Array is a collection of data items of the same type. Array is reference type
so memory for the array is allocated on the heap. Array is a group of
homogeneous data type object. Array is fixed in size.
1. int[]A=new int[6]={1,2,3,4,5,6}
2. for(int i=0;i<6;i++)
3. [Link]=A[i];
*List: an array list that supports generic types and enforces type-safety. Since
it is noncontiguous, it can grow in size without re-allocating memory for
entire list. This is more commonly used list collection.
List<MyClass> list;
1. Collection<int>Student_Id=new int();
2. Collection<string>Student_Name=new String();
3. Collection <string>Course=new string();
Hashes are look-ups in which you give each item in a list a "Key" which will
be used to retrieve it later. Think of a hash like a table index where you can
ask questions like "I am going to find this object by this string value.
Duplicate keys are NOT allowed.
class GFG {
// Main method
static public void Main()
{
// Create a hashtable
// Using Hashtable class
Hashtable my_hashtable = new Hashtable();
class GFG {
// Main Method
static public void Main()
{
// Creating a dictionary
// using Dictionary<TKey, TValue> class
Dictionary<string, string> My_dict =
new Dictionary<string, string>();
Output:
Key:- a.01 and Value:- C
Key:- a.02 and Value:- C++
Key:- a.03 and Value:- C#
Factory design pattern is one of the most used design patterns. In factory
pattern, we create object without exposing the creation logic to the client and
refer to newly created object using a common interface.
Implementation:
[Link]
public interface Shape {
void draw();
}
[Link]
public class Rectangle implements Shape {
@Override
public void draw() {
[Link]("Inside Rectangle::draw() method.");
}
}
[Link]
public class Square implements Shape {
@Override
public void draw() {
[Link]("Inside Square::draw() method.");
}
}
[Link]
public class Circle implements Shape {
@Override
public void draw() {
[Link]("Inside Circle::draw() method.");
}
}
[Link]
public class ShapeFactory {
} else if([Link]("RECTANGLE")){
return new Rectangle();
} else if([Link]("SQUARE")){
return new Square();
}
return null;
}
}
-Step 4: Use the factory to get object of concrete class by passing an
information such as type.
[Link]
public class FactoryPatternDemo {
Serialization Formats:
1- JSON Serialization: "JavaScript Object Notation" is an open standard that
is commonly used for sharing data across the web. JSON serialization
serializes the public properties of an object into a string, byte array, or stream.
[Link] = "Apple";
[Link] = new DateTime(2008, 12, 28);
[Link] = 3.99M;
[Link] = new string[] { "Small", "Medium", "Large" };
Product deserializedProduct =
[Link]<Product>(output);
1. using System;
2. using [Link];
3. using [Link];
4. using [Link];
5.
6. namespace SampleApplication
7. {
8. public partial class ObjectSerialization : [Link]
.[Link]
9. {
10. protected void Page_Load(object sender, Even
tArgs e)
11. {
12. Employees emps = new Employees();
13. [Link](new Employee("1", "Lajapathy"))
;
14. [Link](new Employee("2", "Anand"));
15. [Link](new Employee("3", "Sathiya"));
16.
17. [Link](new Employee("4", "Lakshmi"));
18. [Link](new Employee("5", "Parthiban"))
;
19.
20. string pth = @"D:\[Link]";
21.
22. //Serializing the collection
23. Serialize(emps, pth);
24.
25. //Deserializing the collection
26. Deserialize(pth);
27. }
28. //Serializing the List
29. public void Serialize(Employees emps, String
filename)
30. {
31. //Create the stream to add object into i
t.
32. [Link] ms = [Link](fil
ename);
33.
34. //Format the object as Binary
35. BinaryFormatter formatter = new BinaryFo
rmatter();
36.
37. //It serialize the employee object
38. [Link](ms, emps);
39. [Link]();
40. [Link]();
41. [Link]();
42. }
43. //Deserializing the List
44. public void Deserialize(String filename)
45. {
46. //Format the object as Binary
47. BinaryFormatter formatter = new BinaryFo
rmatter();
48.
49. //Reading the file from the server
50. FileStream fs = [Link](filename, File
[Link]);
51. object obj = [Link](fs);
52. Employees emps = (Employees)obj;
53. [Link]();
54. [Link]();
55. [Link]();
56. foreach (Employee employee in emps)
57. {
58. [Link]([Link] + "<br/
>");
59. }
60. }
61. }
62. //Classes
63. [Serializable]
64. public class Employee
65. {
66. public Employee(String id, String name)
67. {
68. _ID = id;
69. _Name = name;
70. }
71. private String _ID = [Link];
72. private String _Name = [Link];
73. public String ID
74. {
75. get
76. {
77. return _ID;
78.
79. set
80. {
81. _ID = value;
82. }
83. }
84. public String Name
85. {
86. get
87. {
88.
89. return _Name;
90. }
91. set
92. {
93. _Name = value;
94. }
95. }
96. }
97. [Serializable]
98. public class Employees : CollectionBase
99. {
100. //Constructor
101. public Employees()
102. {
103. }
104.
105. //Add function
106. public void Add(Employee objT)
107. {
108. [Link](objT);
109. }
110. //Indexer
111. public Employee this[int i]
112. {
113. get
114. {
115. return (Employee)[Link][i];
116. }
117. set
118. {
119. [Link](value);
120. }
121. }
122. }
123. }
Choose Console Application. In the application first let us write a class with a few
properties.
To serialize this we will use the XmlSerializer class. Write the following code in the
[Link],
Import the following namespaces to use XmlSerializer and TextWriter in the code,
1. using [Link];
2. using [Link];
-Constructor Injection:
void Serve();
this._service = service;
class Program
//creating object
//passing dependency
//TO DO:
//passing dependency
c1 = new Client(s2);
//TO DO:
}
The Injection happens in the constructor, bypassing the Service that
implements the IService interface. The dependencies are assembled by a
"Builder" and Builder responsibilities are as follows:
1. Knowing the types of each IService.
2. According to the request, feed the abstract IService to the Client.
-Property/Setter Injection:
void Serve();
class Program
//creating object
Service1 s1 = new Service1();
//TO DO:
//TO DO:
-Method Injection:
void Serve();
[Link]();
}
}
class Program
//creating object
//TO DO:
MethodInfo Describes the class method and gives access to its metadata
EventInfo Describes the event info and gives accessto its metadata
Example 1:
The MemberInfo object of the [Link] class needs to be initialized for
discovering the attributes associated with a class. To do this, you define an object of
the target class, as −
[Link] info = typeof(MyClass);
[AttributeUsage([Link])]
public class HelpAttribute : [Link] {
public readonly string Url;
namespace AttributeAppl {
class Program {
static void Main(string[] args) {
[Link] info = typeof(MyClass);
object[] attributes = [Link](true);
When it is compiled and run, it displays the name of the custom attributes attached
to the class MyClass −
HelpAttribute
Example 2:
In the code given below, we load the type t as a string using the typeof
method. Then we apply reflection on t to find any information about string
class, like its name, fullname, namespace, and basetype.
// C# program to illustrate
// the use of Reflection
using System;
using [Link];
namespace Reflection_Demo {
class Program {
// Main Method
static void Main(string[] args)
{
// Initialise t as typeof string
Type t = typeof(string);
Output:
Name : String
Full Name : [Link]
Namespace : System
Base Type : [Link]
Example 3:
In this code, we use reflection to show all the metadata related to the
program which includes classes, methods of these classes and the
parameters associated with these parameters.
// C# program to illustrate
// the use of Reflection
using System;
using [Link];
namespace Reflection_Metadata {
// Properties definition
public int RollNo
{
get;
set;
}
public string Name
{
get;
set;
}
// No Argument Constructor
public Student()
{
RollNo = 0;
Name = [Link];
}
// Parameterised Constructor
public Student(int rno, string n)
{
RollNo = rno;
Name = n;
}
class GFG {
// Main Method
static void Main(string[] args)
{
// Declare Instance of class Assembly
// Call the GetExecutingAssembly method
// to load the current assembly
Assembly executing = [Link]();
Output:
Class : Student
--> Method : get_RollNo
--> Method : set_RollNo
----> Parameter : value Type : System.Int32
--> Method : get_Name
--> Method : set_Name
----> Parameter : value Type : [Link]
--> Method : displayData
--> Method : ToString
--> Method : Equals
----> Parameter : obj Type : [Link]
--> Method : GetHashCode
--> Method : GetType
Class : Program
--> Method : ToString
--> Method : Equals
----> Parameter : obj Type : [Link]
--> Method : GetHashCode
--> Method : GetType
Lazy Loading is a concept where we delay the loading of the object until the
point where we need it.
Example:
For example, consider the below example where we have a simple Customer class
and this Customer class has many Order objects inside it. Have a close look at the
constructor of the Customer class. When the Customer object is created it also
loads the Order object at that moment. So even if we need or do not need
the Order object, it’s still loaded.
But how about just loading the Customer object initially and then on demand basis
load the Order object?
Copy Code
public class Customer
{
private List<Order> _Orders= null;
…
…
public Customer()
{
_CustomerName = "Shiv";
_Orders = LoadOrders(); // Loads the order object even though
//not needed
}
So let’s consider you have client code which consumes the Customer class as shown
below. So when the Customer object is created no Order objects should be loaded
at that moment. But as soon as the foreachloop runs you would like to load
the Order object at that point (on demand object loading).
Copy Code
Customer o = new Customer(); // order object not loaded
[Link]([Link]);
foreach (Order o1 in [Link]) // Load order object only at this moment
{
[Link]([Link]);
}
Implementation:
For the above example if we want to implement lazy loading we will need to make
the following changes:
Remove the Order object loading from the constructor.
In the Order get property, load the Order object only if it’s not loaded.
Copy Code
public class Customer
{
private List<Order> _Orders= null;
…
…
public Customer()
{
_CustomerName = "Shiv";
}
public List<Order> Orders
{
get
{
if (_Orders == null)
{
_Orders = LoadOrders();
}
return _Orders;
}
}
Now if you run the client code and halt your debugger just before the foreach loop
runs over the Ordersobject, you can see the Orders object is null (i.e., not
loaded). But as soon as the foreach loop runs over the Order object it creates
the Order object collection.
Readymade objects that are in .NET by which we can implement lazy loading:
In .NET we have the Lazy<T> class which provides automatic support for lazy
loading. So let’s say if you want to implement Lazy<> in the above code, we need to
implement two steps:
Attach this Lazy<> object with the method which will help us load the order’s data.
Copy Code
_Orders = new Lazy<List<Order>>(() => LoadOrders());
Now as soon as any client makes a call to the _Orders object, it will call
the LoadOrders function to load the data.
Copy Code
public List<Order> Orders
{
get
{
return _Orders.Value;
}
Copy Code
public class Customer
{
private Lazy<List<Order>> _Orders= null;
public List<Order> Orders
{
get
{
return _Orders.Value;
}
}
public Customer()
{
// Makes a database trip
_CustomerName = "Shiv";
_Orders = new Lazy<List<Order>>(() => LoadOrders());
}
}
*Code First modeling workflow targets a database that does NOT exist and
Code First will create it. Code First can also be used if you have an empty
database and then Code First will add new tables to it. Code First allows you
to define your model using C# or [Link] classes. Code First is mainly useful
in DOMAIN DRIVEN DESIGN.
*Model First is great for when you are starting a new project where the
database does NOT even exist yet. The model is stored in an EDMX file and
can be viewed and edited in the Entity Framework Designer. In Model First,
you define your model in an Entity Framework Designer then generate SQL,
which will create database schema to match your model and then you execute
the SQL to create the schema in your database.
The classes that you interact with in your application are automatically
generated from the EDMX file.
Example:
Queues control how items in a list are accessed. You typically push/pop
records from queue in a particular direction (from either the front or back).
Not used for random access in the middle.
*Stack: a LIFO (Last In, First Out) list where you push/pop records on top of
each other.
using System;
using [Link];
namespace CollectionsApplication {
class Program {
[Link]('A');
[Link]('B');
[Link]('C');
[Link]('D');
[Link]("Current stack: ");
[Link]();
[Link]('P');
[Link]('Q');
[Link]();
[Link]("Removing values....");
[Link]();
[Link]();
[Link]();
}
}
Output:
Current stack:
D C B A
The next poppable value in stack: Q
Current stack:
Q P D C B A
Removing values....
Current stack:
C B A
*Queue: a FIFO (First In, First Out) list where you push/pop records on top
and pop them off the bottom.
Enqueue
Add items in the queue.
Queue q = new Queue();
[Link](“Two”);
[Link](“One”);
Dequeue
Return items from the queue.
// remove elements
while ([Link] > 0)
[Link]([Link]());
1. using System;
2. namespace example_enum {
3. class Program {
4. public enum DayofWeek {
5. Sunday = 1, Monday, Tuesday, Wednesday, Thurs
day, Friday, Saturday
6. }
7. static void Main(string[] args) {
8. [Link]("Day of week {0} {1}", (int
) [Link], [Link]);
9. [Link]("Day of week {0} {1}", (int
) [Link], [Link]);
10. [Link]("Day of week {0} {1}",
(int) [Link], [Link]);
11. [Link]("Day of week {0} {1}",
(int) [Link], [Link]);
12. [Link]("Day of week {0} {1}",
(int) [Link], [Link]);
13. [Link]("Day of week {0} {1}",
(int) [Link], [Link]);
14. [Link]("Day of week {0} {1}",
(int) [Link], [Link]);
15. [Link]();
16. }
17. }
18. }
We can have the same value in the enum type. For example- when we want to
set priority options like,
Normal 0
Excellent 1
Default 0
Good 3
1. using System;
2. namespace enum_example4 {
3. class Program {
4. public enum DayofWeek {
5. Sunday = 1, Monday, Tuesday = 1, Wednesday, T
hursday = 2, Friday, Saturday
6. }
7. static void Main(string[] args) {
8. string[] values = [Link](typeof(DayofW
eek));
9. foreach(string s in values) {
10. [Link](s);
11. }
12. [Link]();
13. int[] n = (int[]) [Link](typeof(
DayofWeek));
14. foreach(int x in n) {
15. [Link](x);
16. }
17. [Link]();
18. }
19. }
20. }
1. using System;
2. namespace enum_exampl3 {
3. class Program {
4. public enum DayofWeek {
5. Sunday = 1, Monday, Tuesday, Wednesday, Thurs
day, Friday, Saturday
6. }
7. static void Main(string[] args) {
8. string[] values = [Link](typeof(DayofW
eek));
9. int total = 0;
10. foreach(string s in values) {
11. [Link](s);
12. total++;
13. }
14. [Link]("Total values in enum
type is : {0}", total);
15. [Link]();
16. int[] n = (int[]) [Link](typeof(
DayofWeek));
17. foreach(int x in n) {
18. [Link](x);
19. }
20. [Link]();
21. }
22. }
23. }
Constant variables are declared and initialized at compile time. The value can't
be changed afterward. Read-only is used only when we want to assign the value
at run time.
*Constants:
Constants are static by default.
They must have a value at compilation-time (you can have e.g.,
3.14*2+5, but can NOT call methods).
could be declared within functions.
These are copied into every assembly that uses them (every assembly
gets a local copy of values).
1. using System;
2. namespace ConstantExample
3. {
4. class ConstantExample
5. {
6. private const int PI = 3.14;
7. public static void Main()
8. {
9. //You have to initialize Const variables whil
e declaration
10. const int RollNo = 1284;
11. //Valid scenario
12. const int Age = 10 + 13;
13. const string Name = "Satish Kumar";
14.
15. // Reassigning a const variable is not a
llowed.
16.
RollNo = 1405; // Will result compile time error.
17. Age+
+; // Will result compile time error.
18. [Link](Name);
19.
20. [Link]();
21. }
22. }
23. }
*Readonly:
Must have set value, by the time constructor exits.
Are evaluated when instance is created.
You can use static modifier for readonly fields.
Readonly modifier can be used with reference types.
Readonly modifier can be used only for instance or static fields, you
can NOT use readonly keyword for variables in the methods.
1. using System;
2.
3. namespace ReadOnlyExample
4. {
5. class ReadOnlyTest
6. {
7. //You have to initilize readonly varabiles while de
claration or in constructor
8. readonly int RollNo = 1284;
9.
10. //Valid scenario
11. readonly int Age;
12.
13. readonly string Name = "Satish Kumar";
14.
15. //readonly fields can be initlized in construc
tor
16. public ReadOnlyTest (string name)
17. {
18. Age = 23;
19. Name = name;
20. }
21.
22. public changeName(string newName)
23. {
24. Name = "Satish Kumar Vadlavalli"; ; // W
ill result error.
25. }
26. }
27.
28. class ReadOnlyExample
29. {
30. public static void Main()
31. {
32.
ReadOnlyTest obj = new ReadOnlyTest("Satish");
33. [Link]();
34. }
35. }
36. }
const fields has to be initialized while declaration only, while readonly fields
can be initialized at declaration or in the constructor.
const variables can declared in methods ,while readonly fields cannot be
declared in methods.
const fields can NOT be used with static modifier, while readonly fields can be
used with static modifier.
A const field is a compile-time constant, the readonly field can be used for run
time constants.
In C#, readonly fields can be created using In C#, constant fields are created
readonly keyword using const keyword.
In readonly fields, we can assign values in In const fields, we can only assign
declaration and in the contructor part. values in declaration part.
namespace ExtensionMethod {
// Method 1
public void M1()
{
[Link]("Method Name: M1");
}
// Method 2
public void M2()
{
[Link]("Method Name: M2");
}
// Method 3
public void M3()
{
[Link]("Method Name: M3");
}
}
namespace ExtensionMethod {
// Method 4
public static void M4(this Geek g)
{
[Link]("Method Name: M4");
}
// Method 5
public static void M5(this Geek g, string str)
{
[Link](str);
}
}
// Main Method
public static void Main(string[] args)
{
Geek g = new Geek();
g.M1();
g.M2();
g.M3();
g.M4();
g.M5("Method Name: M5");
}
}
}
Output:
Method Name: M1
Method Name: M2
Method Name: M3
Method Name: M4
Method Name: M5
Notes:
Binding Parameters are those parameters which are used to bind the
new method with the existing class or structure. It does NOT take any
value when you are calling the extension method because they are used
only for binding NOT for any other use. In the parameter list of the
extension method binding parameter is always present at the first place.
If you write binding parameter to second, or third, or any other place
rather than first place then the compiler will give an ERROR. The
Binding Parameter is created using "this" Keyword followed by the
name of the class in which you want to add a new method and the
parameter name. For example: this Geek g
Here, "this" keyword is used for binding, Geek is the class name in which
you want to bind, and g is the parameter name.
Extension methods are always defined as a static method, but when
they are bound with any class or structure, they will convert into non-
static methods.
When an extension method is defined with the same name and the
signature of the existing method, then the complier will print the
existing method, NOT the extension method. Or in other words, The
extension method does NOT support method overriding.
You can also add new methods in the sealed class also using an
extension method concept.
It can NOT apply to fields, properties or events.
It must be defined in top-level static class.
Multiple binding parameters are NOT allowed, means an extension
method only contains a single binding parameter. But you can define
one or more normal parameter in the extension method.
The main advantage of the extension method is to add new methods in the
existing class without using Inheritance.
The delegate is a reference type data type that defines the method signature.
You can define variables of delegate, just like other data type, that can refer
to any method with the same signature as the delgate.
Delegate Syntax:
Implementation:
-Step 1: Create a Singleton Class.
[Link]
public class SingleObject {
[Link]
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not
visible
//SingleObject object = new SingleObject();
21- What are the differences between "readonly", "const", "static" and
"partial"?
22- What are the differences between "ref" and "out" Keywords?
23- What are the differences between "Equality operator ==" and "Equals()"
method in C#?
24- What are the differences between "&" operator and "&&" operator?
25- What is the difference between [Link]() and
[Link]()?
26- What is multicast delegate?
27- What are the differences between Dataset and DataReader?
28- What are the differences between Single(), Take(), Skip(), First() and
FirstOrDefault()?