0% found this document useful (0 votes)
8 views45 pages

Interview Questions

The document provides a comprehensive overview of various C# concepts, including differences between control flow statements, type operators, data structures like arrays and hashtables, factory design patterns, and serialization techniques. It explains the functionality and use cases of each concept with code examples and outputs. Additionally, it covers serialization formats such as JSON, binary, and XML, detailing how to implement them in C#.

Uploaded by

nourhan.fares
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views45 pages

Interview Questions

The document provides a comprehensive overview of various C# concepts, including differences between control flow statements, type operators, data structures like arrays and hashtables, factory design patterns, and serialization techniques. It explains the functionality and use cases of each concept with code examples and outputs. Additionally, it covers serialization formats such as JSON, binary, and XML, detailing how to implement them in C#.

Uploaded by

nourhan.fares
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Interview Questions

C#:

1- What are the differences between "continue" and "break" statements in C#?
Ans:

"Break" causes the innermost enclosing loop or switch to be exited


immediately.
Whereas the "continue" statement causes the next iteration of the enclosing
loop to begin.

2- What is the difference between "is" and "as" operator in C#?


Ans:

"is" operator checks whether the runtime type of an expression's result is


compatible with a given type or not. The "is" operator is Boolean type. The
"is" operator is used only for reference, boxing and unboxing conversions.

static void testClass(object o)


{
if(o is Student)
{ [Link]($"The instance: {nameof(o)} we
recieved as argument is from Student class!"); }
else if(o is Teacher)
{ [Link]($"The instance: {nameof(o)} we
recieved as argument is from Teacher class!"); }
else
{ [Link]($"The instance: {nameof(o)} we
recieved as argument is from neither Teacher nor Student class!"); }
}
static void Main(string[] args)
{
Student s = new Student();
Teacher t = new Teacher();
int i = 0;
testClass(s);
testClass(t);
testClass(i);
[Link](); ;
}
Output:
The instance: o we recieved as argument is from Student class!
The instance: o we recieved as argument is from Teacher class!
The instance: o we recieved as argument is from neither Teacher nor
Student class!

"as" operator is used to perform conversions between compatible types. It has


a very similar role to the "is" operator, however, it works differently under
the hood. "as" operator is NOT Boolean type. "as" operator returns the
object when they are compatible with the given type and returns NULL if the
conversion is not possible. "as" operator is used only for nullable, reference
and boxing conversions.

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:

Inspecting element: [Link] ->> Incompatible type, with string!


Inspecting element: [Link] ->> Incompatible type, with string!
Inspecting element: Student ->> Compatible type, with string!
Inspecting element: Teacher ->> Compatible type, with string!

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;

*Collection: is group of homogeneous and heterogeneous data type object.


Collection is not fixed in size. Collection supports generic types.

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.

*Hashtable is non-generic collection. It is defined under [Link]


namespace. In Hashtable, you can store Key/Value pairs of the same type or
of the different type. In Hashtable, there is no need to specify the type of the
key and value. The data retrieval is slower than Dictionary due to
boxing/unboxing. In Hashtable, if you try to access a key that does NOT
present in the given Hashtable, then it will give NULL values. Hashtable is
thread safe. Hashtable does NOT maintain the order of stored values.
// C# program to illustrate a hashtable
using System;
using [Link];

class GFG {

// Main method
static public void Main()
{

// Create a hashtable
// Using Hashtable class
Hashtable my_hashtable = new Hashtable();

// Adding key/value pair in the hashtable


// Using Add() method
my_hashtable.Add("A1", "Welcome");
my_hashtable.Add("A2", "to");
my_hashtable.Add("A3", "GeeksforGeeks");

foreach(DictionaryEntry element in my_hashtable)


{
[Link]("Key:- {0} and Value:- {1} ",
[Link], [Link]);
}
}
}
Output:

Key:- A3 and Value:- GeeksforGeeks


Key:- A2 and Value:- to
Key:- A1 and Value:- Welcome

*Dictionary is a generic collection. Dictionary is defined under


[Link] namespace. In Dictionary, you can store
Key/Value pairs of same type. In Dictionary and on the contrary to
Hashtable, you MUST specify the type of Key and Value. The date retrieval is
faster than hashtable due to no boxing/unboxing. In Dictionary, if you try to
access a key that does NOT present in the given Dictionary, then it will give
ERROR. It is also thread safe as hashtable but only for public static
members. On the contrary to Hashtable, Dictionary ALWAYS maintain the
order of stored values.
// C# program to illustrate Dictionary
using System;
using [Link];

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>();

// Adding key/value pairs in the Dictionary


// Using Add() method
My_dict.Add("a.01", "C");
My_dict.Add("a.02", "C++");
My_dict.Add("a.03", "C#");

foreach(KeyValuePair<string, string> element in My_dict)


{
[Link]("Key:- {0} and Value:- {1}",
[Link], [Link]);
}
}
}

Output:
Key:- a.01 and Value:- C
Key:- a.02 and Value:- C++
Key:- a.03 and Value:- C#

4- What is Factory Design Patterns?


Ans:

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:

-Step 1: Create an interface

[Link]
public interface Shape {
void draw();
}

-Step 2: Create concrete classes implementing the same interface.

[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.");
}
}

-Step 3: Create a factory to generate object of concrete class based on given


information.

[Link]
public class ShapeFactory {

//use getShape method to get object of type shape


public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if([Link]("CIRCLE")){
return new Circle();

} 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 {

public static void main(String[] args) {


ShapeFactory shapeFactory = new ShapeFactory();

//get an object of Circle and call its draw method.


Shape shape1 = [Link]("CIRCLE");

//call draw method of Circle


[Link]();

//get an object of Rectangle and call its draw method.


Shape shape2 = [Link]("RECTANGLE");

//call draw method of Rectangle


[Link]();

//get an object of Square and call its draw method.


Shape shape3 = [Link]("SQUARE");

//call draw method of square


[Link]();
}
}

5- What is the Serialization and its types?


Ans:

Serialization is the process of converting an object into a stream of bytes to


store the object or transmit it to memory, a database, or a file. Its main
purpose is to save the state of an object in order to recreate it when needed.
The reverse process is called Deserialization.
The object is serialized to a stream that carries the data. The stream may also
have information about the object's type, such as its version, culture, and
assembly name. From that stream, the object can be stored in a database, a
file, or memory.

Through serialization, developers can perform actions such as:


 Sending the object to a remote application by using a web service.
 Passing an object from one domain to another.
 Passing an object through a firewall as a JSON or XML string.
 Maintaining Security or use-specific information across applications.

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.

-JsonConvert: to convert to and from a JSON String.

Product product = new Product();

[Link] = "Apple";
[Link] = new DateTime(2008, 12, 28);
[Link] = 3.99M;
[Link] = new string[] { "Small", "Medium", "Large" };

string output = [Link](product);


//{
// "Name": "Apple",
// "ExpiryDate": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}

Product deserializedProduct =
[Link]<Product>(output);

-JsonSerializer: For more control over how an object is serialized.


JsonSerializer is able to read and write JSON text directly to a stream via
JsonTextReader and JsonTextWriter. Other Kinds of JsonWriters can aslo be
used, such as JTokenReader/JTokerWriter to convert your object to and from
LINQ to JSON objects, or BsonReader/BsonWriter to convert to and from
BSON.

Product product = new Product();


[Link] = new DateTime(2008, 12, 28);

JsonSerializer serializer = new JsonSerializer();


[Link](new JavaScriptDateTimeConverter());
[Link] = [Link];

using (StreamWriter sw = new StreamWriter(@"c:\[Link]"))


using (JsonWriter writer = new JsonTextWriter(sw))
{
[Link](writer, product);
// {"ExpiryDate":new Date(1230375600000),"Price":0}
}

2- Binary and XML Serialization:


Binary Serialization uses binary encoding to produce compact serialization
for uses such as Storage or Socket-based network Streams. In binary
serialization, all members, even members that are read-only are serialized and
performance is enhanced.

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. }

XML Serialization serializes the public field and properties of an object, or


the parameters and return values of methods, into an XML stream that
conforms to a specific XML schema definition Language XSD document.

Choose Console Application. In the application first let us write a class with a few
properties.

1. public class Employee


2. {
3. public int Id = 1;
4. public String name = "John Smith";
5. public string subject = "Physics";
6. }

To serialize this we will use the XmlSerializer class. Write the following code in the
[Link],

1. static void Main(string[] args)


2. {
3. Employee bs = new Employee();
4.
5. XmlSerializer xs = new XmlSerializer(typeof(Employee)
);
6.
7. TextWriter txtWriter = new StreamWriter(@ "D:\
[Link]");
8.
9. [Link](txtWriter, bs);
10.
11. [Link]();
12.
13. }

Import the following namespaces to use XmlSerializer and TextWriter in the code,

1. using [Link];
2. using [Link];

To prevent a field from being serialized, apply the "NonSerializedAttribute"


attribute.

6- What is the difference between Reflection and Dependency injection?


Ans:

*Dependency Injection is a software design pattern that allows us to develop


loosely coupled code. It is a great way to reduce tight coupling between
software components. Dependency Injection also enables us to better manage
future changes and other complexity in our software. its purpose is to make
code maintainable.

The dependency Injection pattern uses a builder object to initialize objects


and provide the required dependencies to the object. Means it allows you to
"inject" a dependency from outside the class.
For example, Suppose your Client class needs to use two service classes,
then the best you can do is to make your Client class aware of abstraction
i.e. IService interface rather than implementation
i.e. Service1 and Service2 classes. In this way, you can change the
implementation of the IServiceinterface at any time (and for how many
times you want) without changing the client class code.

We can modify this code by following the Dependency Injection


Implementation ways. We have the following different ways to implement
Dependency Injection:

-Constructor Injection:

public interface IService {

void Serve();

public class Service1 : IService {

public void Serve() { [Link]("Service1 Called"); }

public class Service2 : IService {


public void Serve() { [Link]("Service2 Called"); }

public class Client {

private IService _service;

public Client(IService service) {

this._service = service;

public ServeMethod() { this._service.Serve(); }

class Program

static void Main(string[] args)

//creating object

Service1 s1 = new Service1();

//passing dependency

Client c1 = new Client(s1);

//TO DO:

Service2 s2 = new Service2();

//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:

public interface IService {

void Serve();

public class Service1 : IService {

public void Serve() { [Link]("Service1 Called"); }

public class Service2 : IService {

public void Serve() { [Link]("Service2 Called"); }

public class Client {

private IService _service;

public IService Service {

set { this._service = value; }

public ServeMethod() { this._service.Serve(); }

class Program

static void Main(string[] args)

//creating object
Service1 s1 = new Service1();

Client client = new Client();

[Link] = s1; //passing dependency

//TO DO:

Service2 s2 = new Service2();

[Link] = s2; //passing dependency

//TO DO:

-Method Injection:

public interface IService {

void Serve();

public class Service1 : IService {

public void Serve() { [Link]("Service1 Called"); }

public class Service2 : IService {

public void Serve() { [Link]("Service2 Called"); }

public class Client {

private IService _service;

public void Start(IService service) {

[Link]();

}
}

class Program

static void Main(string[] args)

//creating object

Service1 s1 = new Service1();

Client client = new Client();

[Link](s1); //passing dependency

//TO DO:

Service2 s2 = new Service2();

[Link](s2); //passing dependency

Advantages of Dependency Injection:


1. Reduces Class Coupling.
2. Increase Code reusability.
3. Improve code maintainability.
4. Make Unit testing possible.

*Reflection: reflection objects are used for obtaining type information at


runtime. The Classes that give access to the metadata of a running program
are in the [Link] namespace. (Reflection is the process of
describing the metadata of types, methods and fields in a code).

[Link] namespace contains classes that allow you to Obtain


Information about the application and to dynamically add types, values, and
objects to the application.
Some of the commonly used classes of [Link] are:
Class Description

describes an assembly which is a reusable, versionable, and self-


describing building block of a common language runtime
Assembly application

AssemblyName Identifies an assembly ith a unique name

ConstructorInfo Describes a class constructor and gives access to the metadata

MethodInfo Describes the class method and gives access to its metadata

Describes the parameters of a method and gives access to its


ParameterInfo metadata

EventInfo Describes the event info and gives accessto its metadata

Discovers the attributes of a property and provides access to


PropertyInfo property metadata

Obtains information about the attributes of a member and


MemberInfo provides access to member metadata

Reflection has the following applications:


 It allows view attribute information at runtime.
 It allows examining various types in an assembly and instantiate these
types.
 It allows late binding to methods and properties.
 It allows creating new types at runtime and then performs some tasks
using those types.

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);

The following program demonstrates this −


using System;

[AttributeUsage([Link])]
public class HelpAttribute : [Link] {
public readonly string Url;

public string Topic // Topic is a named parameter {


get {
return topic;
}
set {
topic = value;
}
}
public HelpAttribute(string url) // url is a positional
parameter {
[Link] = url;
}
private string topic;
}

[HelpAttribute("Information on the class MyClass")]


class MyClass {

namespace AttributeAppl {
class Program {
static void Main(string[] args) {
[Link] info = typeof(MyClass);
object[] attributes = [Link](true);

for (int i = 0; i < [Link]; i++) {


[Link](attributes[i]);
}
[Link]();
}
}
}

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);

// Use Reflection to find about


// any sort of data related to t
[Link]("Name : {0}", [Link]);
[Link]("Full Name : {0}", [Link]);
[Link]("Namespace : {0}", [Link]);
[Link]("Base Type : {0}", [Link]);
}
}
}

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 {

// Define a class Student


class Student {

// 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;
}

// Method to Display Student Data


public void displayData()
{
[Link]("Roll Number : {0}", RollNo);
[Link]("Name : {0}", Name);
}
}

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]();

// Array to store types of the assembly


Type[] types = [Link]();
foreach(var item in types)
{
// Display each type
[Link]("Class : {0}", [Link]);

// Array to store methods


MethodInfo[] methods = [Link]();
foreach(var method in methods)
{
// Display each method
[Link]("--> Method : {0}", [Link]);

// Array to store parameters


ParameterInfo[] parameters = [Link]();
foreach(var arg in parameters)
{
// Display each parameter
[Link]("----> Parameter : {0} Type : {1}",
[Link], [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

7- What is the lazy loading in C#?


Ans:

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
}

private List<Order> LoadOrders()


{
List<Order> temp = new List<Order>();
Order o = new Order();
[Link] = "ord1001";
[Link](o);
o = new Order();
[Link] = "ord1002";
[Link](o);
return temp;
}
}

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:

Create the object of orders using the Lazy generic class.


Copy Code
private Lazy<List<Order>> _Orders= null;

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.

You will get the List<orders> data in the Value property.

Copy Code
public List<Order> Orders
{
get
{
return _Orders.Value;
}

Below goes the full code for this:

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());
}
}

Advantages of Lazy Loading:


 Minimize start up time of the application.
 Application consumes less memory because of on-demanding loading.
 Unnecessary database SQL execution is avoided.
Disadvantages:
The only on disadvantage is that the code becomes complicated. As we need to
check if the loading is needed or not, there is a slight decrease in
performance.

8- What is Code First? and What is Database First?


Ans:

*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.

In the Code-First approach, you focus on the domain of your application


and start creating classes for your domain entity rather than design your
database first and then create the classes which match your database
design. The following figure illustrates the code-first approach.
Code First is really made up of a set of puzzle pieces.
1. First are your domain classes. The domain classes have nothing to do
with Entity Framework. They are just the items of your business
domain.
2. Entity Framework, then, has a context that manages the interaction
between those classes and your database. The context is NOT specified
to Code First. It is an Entity Framework feature.
3. Code First adds a model builder that inspects your classes that the
context is managing, and then uses a set of rules or conventions to
determine how those classes and the relationships describe a model,
and how that model should map to your database. All of this happens at
runtime. You will NEVER see this model. It is just in memory.
Code First also has the ability to use that model to create a database if you
wanted to. It can also update the database if the model changes, using a
feature called Code First Migrations.

Code First Workflow:

The development workflow in the code-first approach would be: Create or


modify domain classes -> configure these domain classes using Fluent-API
or data annotation attributes -> Create or update the database schema
using automated migration or code-based migration.

*Database First creates model codes (classes, properties, DbContext, etc)


from the database in the project and those classes become the link between
the database and controller. The Database First approach creates the Entity
Framework from an existing database. We use all other functionalities, such
as the model/database sync and the code generation, in the same way we used
them in the Model First approach.

*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.

9- What are the differences between Lambda and LINQ?


Ans:

*Language -Integrated Query (LINQ) is a set of features introduced in Visual


Studio 2008 that extends powerful query capabilities to the language syntax
of C# and VB.

*Lambda expression is an anonymous function that you can use to create


delegates or expression free types. By using Lambda expressions, you can
write local functions that can be passed as arguments or returned as the value
of function calls.

LINQ uses Lambda expression in order to execute some of its functionalities.

Example:

new [] { "Dan", "Yossi", "Ben" }.Where(item => [Link] == 3);


Lambda expression: item => [Link] == 3
Linq: (from item in (new [] { "Dan", "Yossi", "Ben" }) where [Link] ==
3)

10- What are the differences between Queues and Stacks?


Ans:

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 {

static void Main(string[] args) {

Stack st = new Stack();

[Link]('A');

[Link]('B');

[Link]('C');

[Link]('D');
[Link]("Current stack: ");

foreach (char c in st) {

[Link](c + " ");

[Link]();

[Link]('P');

[Link]('Q');

[Link]("The next poppable value in stack:


{0}", [Link]());

[Link]("Current stack: ");

foreach (char c in st) {

[Link](c + " ");

[Link]();

[Link]("Removing values....");

[Link]();

[Link]();

[Link]();

[Link]("Current stack: ");

foreach (char c in st) {

[Link](c + " ");

}
}

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.

Queue q = new Queue();


[Link](“Two”);
[Link](“One”);

// remove elements
while ([Link] > 0)
[Link]([Link]());

11-What is Boxing? and What is Unboxing?


Ans:

C# Type System contains three data types:


Value Types (int, char, etc) are always stored in STACK.
Reference Types (Object) is stored in HEAP.
Pointer Types.
*Boxing: is the process of Converting a Value Type (char, int, etc) to a
Reference Type (Object). Boxing is "Implicit" conversion process in which
object type (super Type) is used.

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


Object Obj = num; // Boxing
*Unboxing is the process of converting Reference Type (Object) into Value
Type. Unboxing is "Explicit" conversion process.

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


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

12- What is enum in C#?


Ans:

An enum is a special "class" that represents a group of constants


(Unchangeable/Read-only variables). enum is a value type with a set of
related named constants often referred as an enumerator list. Enum is a
primitive data type, which is user defined. All members of the enum are of
enum type. There much be a numeric value for each enum type. The default
underlying type of the enumeration elements is int. By default, the first
enumerator has value 0, and the value of each successive enumerator is
increased by 1.

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

Program showing enum type having same values

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. }

Program to find out the number of values in enum

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. }

13- What is the difference between "constant" and "readonly" in C#?


Ans:

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. }

Difference between const and readonly

 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.

ReadOnly Vs Const Keyword


ReadOnly Keyword Const Keyword

In C#, readonly fields can be created using In C#, constant fields are created
readonly keyword using const keyword.

ReadOnly is a runtime constant. Const is a compile time constant.


The value of the const field can not
The value of readonly field can be changed. be changed.

It can be declared inside the


It cannot be declared inside the method. method.

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.

It cannot be used with static


It can be used with static modifiers. modifiers.

14- What is the extension method in C# and how to use them?


Ans:

Extension methods allows developers to extend functionality of an existing


type without creating a new derived type, recompiling, or otherwise modifying
the original type. Extension method is a special kind of static method that is
called as if it was an instance method on the extended type.

Extension method is a static method of a static class, where the "this"


modifier is applied to the first parameter. The type of the first parameter will
be the type that is extended. Extension methods are only in scope when you
explicitly import the namespace into your source code with a using directive.
Example:
First we create a class named as Geek in [Link] file. It contains three
methods that is M1(), M2(), and M3().
// C# program to illustrate the concept
// of the extension methods
using System;

namespace ExtensionMethod {

// Here Geek class contains three methods


// Now we want to add two more new methods in it
// Without re-compiling this class
class Geek {

// 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");
}
}

Now we create a static class named as NewMethodClass


in [Link] file. It contains two methods that are M4() and M5(). Now we
want to add these methods in Geek class, so we use the binding
parameter to bind these methods with Geek class. After that, we create
another named as GFG in which Geek class access all the five methods.

// C# program to illustrate the concept


// of the extension methods
using System;

namespace ExtensionMethod {

// This class contains M4 and M5 method


// Which we want to add in Geek class.
// NewMethodClass is a static class
static class NewMethodClass {

// 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);
}
}

// Now we create a new class in which


// Geek class access all the five methods
public class GFG {

// 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.

15- What is the difference between String and StringBuilder in C#?


Ans:

[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.

16- What are delegates and the uses of delegates in C#?


Ans:

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.

There are 3 steps involved while working with delegates:


1. Declare a delegate.
2. Set a target method.
3. Invoke a delegate.

A delegate can be declared using the "delegate" keyword followed by a


function signature.

Delegate Syntax:

[access modifier] delegate [return type] [delegate name]([parameters])

17- What are the differences between IEnumerable and IQueryable?


18- What happens if the inherited interfaces have conflicting method names?
19- What is the Constructor Chaining in C#?
20- What is Singleton Design Pattern and how to implement it?
Ans:

Singleton design pattern comes under creational pattern as this pattern


provides one of the best ways to create an Object.

Implementation:
-Step 1: Create a Singleton Class.

[Link]
public class SingleObject {

//create an object of SingleObject


private static SingleObject instance = new SingleObject();

//make the constructor private so that this class cannot be


//instantiated
private SingleObject(){}

//Get the only object available


public static SingleObject getInstance(){
return instance;
}

public void showMessage(){


[Link]("Hello World!");
}
}

-Step 2: Get the only Object from the singleton class.

[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();

//Get the only object available


SingleObject object = [Link]();

//show the message


[Link]();
}
}

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()?

You might also like