C#


What’s the difference between IEnumerable<T> and List<T>?
  1. IEnumerable is an interface, whereas List is one specific implementation of IEnumerable. A list is a class.
  2. FOR-EACH loop is the only possible way to iterate through a collection of IEnumerable whereas List can be iterated using several ways. The list can also be indexed by an int index, the element can be added to and removed from and have items inserted at a particular index.
  3. IEnumerable doesn’t allow random access, whereas List does allow random access using the integral index.
  4. In general from a performance standpoint, iterating through IEnumerable is much faster than iterating thru a List

What is the difference between IEnumerable and IQueryable in C#?

  • IEnumerable exists in System.Collections Namespace.
  • IQueryable exists in System. Linq Namespace.
  • Both IEnumerable and IQueryable are forward collection.
  • IEnumerable doesn’t support lazy loading
  • IQueryable support lazy loading
  • Querying data from a database, IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data.
  • Querying data from a database, IQueryable execute the select query on the server side with all filters.
  • IEnumerable Extension methods take functional objects.
  • IQueryable Extension methods take expression objects means expression tree.

What is the difference between ienumerable and enumerator

IEnumerable is an interface that defines one method GetEnumerator which returns an IEnumerator interface, this in turn allows readonly access to a collection. A collection that implements IEnumerable can be used with a foreach statement.

Definition

IEnumerable 

public IEnumerator GetEnumerator();

IEnumerator

public object Current;
public void Reset();
public bool MoveNext();

example code from codebetter.com

An IEnumerator is a thing that can enumerate: it has the Current property and the MoveNext and Reset methods (which in .NET code you probably won’t call explicitly, though you could).

An IEnumerable is a thing that can be enumerated…which simply means that it has a GetEnumerator method that returns an IEnumerator.

Which do you use? The only reason to use IEnumerator is if you have something that has a nonstandard way of enumerating (that is, of returning its various elements one-by-one), and you need to define how that works. You’d create a new class implementing IEnumerator. But you’d still need to return that IEnumerator in an IEnumerable class.

For a look at what an enumerator (implementing IEnumerator<T>) looks like, see any Enumerator<T> class, such as the ones contained in List<T>Queue<T>, or Stack<T>. For a look at a class implementing IEnumerable, see any standard collection class.

Can you explain Lazy Loading?

Lazy loading is a concept where we delay the loading of the object until the point where we need it. Putting in simple words, on demand object loading rather than loading objects unnecessarily.

Can an Interface contain fields? -No, an Interface cannot contain fields
Can an interface inherit from another interface?

Yes, an interface can inherit from another interface. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members.

If a class inherits an interface, what are the 2 options available for that class?

Option1: Provide Implementation for all the members, inherited from the interface.
Option2: If the class does not wish to provide Implementation for all the members inherited from the interface, then the class has to be marked as abstract

When to use Abstract Classes in C#?

When we have a requirement where our base class should provide the default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

Can an abstract class have a constructor? If so what is the use?

Yes, an abstract class can have a constructor. In general, a class constructor is used to initialize fields. Along the same lines, an abstract class constructor is used to initialize fields of the abstract class. We would provide a constructor for an abstract class if we want to initialize certain fields of the abstract class before the instantiation of a child-class takes place. An abstract class constructor can also be used to execute code that is relevant for every child’s class. This prevents duplicate code.

We cannot create an instance of an abstract class. So, what is the use of a constructor in an abstract class?

Though we cannot create an instance of an abstract class, we can create instances of the classes that are derived from the abstract class. So, when an instance of a derived class is created, the parent abstract class constructor is automatically called.

Note: Abstract classes can’t be directly instantiated. The abstract class constructor gets executed through a derived class. So, it is a good practice to use a protected access modifier with the abstract class constructor. Using public doesn’t make sense. 

When should a method be declared as sealed in C#?

If we don’t want to allow subclasses to override the superclass method and to ensure that all sub-classes use the same superclass method logic then that method should be declared as sealed.

The sealed method cannot be overridden in sub-classes violation leads to a Compile-time error:

What type of members can we define in an abstract class?

We can define all static and non-static members including properties, fields, indexes and also abstract methods.

Can we declare the abstract method as static?

No, we are not allowed to declare the abstract method as static. It leads to CE: the illegal combination of modifier abstract and static. If the compiler allows us to declare it as static, it can be invoked directly which cannot be executed by CLR at runtime. Hence to restrict in calling abstract methods compiler does not allow us to declare the abstract method as static.

Can we declare the concrete class as abstract?

Yes, it is allowed. Defining a class as abstract is a way of preventing someone from instantiating a class that is supposed to be extended first. To ensure our class non-static members are only accessible via sub-class object we should declare the concrete class as abstract.

Can fields inside a class be virtual?

No, Fields inside a class cannot be virtual. Only methods, properties, events and indexers can be virtual.

Can you access a hidden base class method in the derived class? 

Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the derived class to an instance of the base class as shown in the example below.

public class BaseClass
{
    public virtual void Method()
    {
        Console.WriteLine("I am a base class method.");
    }
}
public class DerivedClass : BaseClass
{
    public new void Method()
    {
        Console.WriteLine("I am a child class method.");
    }

    public static void Main()
    {
        DerivedClass DC = new DerivedClass();
        ((BaseClass)DC).Method();
    }
}

Is it possible to create partial structs, interfaces, and methods in C#?

Yes, it is possible to create partial structs, interfaces, and methods. We can create partial structs, interfaces, and methods in the same way as we create partial classes.

What is a Constructor in C#?

Constructors are the special types of methods of a class that get executed when its object is created. The Constructors in C# are responsible for object initialization and memory allocation of its class and the new keyword role is creating the object.

What is a copy constructor in C#?

The constructor takes a parameter of class type is called the copy constructor and this constructor is used to copy one object data into another object
-The main purpose of the copy constructor is to initialize a new object (instance) with the values of an existing object (instance).
That means this constructor is used to copy the data of an existing object into a newly created object that’s why this constructor is called the copy constructor

https://www.geeksforgeeks.org/c-sharp-copy-constructor/

https://www.tutlane.com/tutorial/csharp/csharp-copy-constructor-with-examples

Can we initialize non-static data fields within the static constructor?

It is not possible to initialize non-static data fields within the static constructor, it raises a compilation error.

Can we initialize static data fields within the non-static constructor?

Yes, we can initialize static data fields within a non-static constructor but after then they lose their static nature.

When is a destructor method called?

A destructor method gets called when the object of the class is destroyed.

When will be the object of a class gets destroyed?

The object of a class will be destroyed by the garbage collector in any of the following cases

Case1: At the end of a program execution each and every object that is associated with the program will be destroyed by the garbage collector.

Case2: The Implicit calling of the garbage collector occurs sometime in the middle of the program execution provided the memory is full so that the garbage collector will identify unused objects of the program and destroys them.

Case3: The Explicit calling of the garbage collector can be done in the middle of program execution with the help of “GC.Collect()” statement so that if there are any unused objects associated with the program will be destroyed in the middle of the program execution by the garbage collector.

Can you mark a static constructor with access modifiers?

No, we cannot use access modifiers on the static constructor.

Can you have parameters for static constructors?

No, static constructors cannot have parameters.

What happens if a static constructor throws an exception?

If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Give 2 scenarios where static constructors can be used?

A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Static constructors are also useful when creating wrapper classes for unmanaged code when the constructor can call the Load Library method.

Why is it not a good idea to use Empty destructors? 

When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.

What is the difference between string keyword and System.String class? 

string keyword is an alias for System.String class. Therefore System.String and string keyword are the same, and we can use whichever naming convention we prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.

How do you determine whether a String represents a numeric value?

To determine whether a String represents a numeric value use TryParse method as shown in the example below. If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.

string str = "One";
int i = 0;

if(int.TryParse(str,out i))
{
     Console.WriteLine("Yes string contains Integer and it is " + i);
}
else
{
     Console.WriteLine("string does not contain Integer");
}
What is the difference between int.Parse and int.TryParse methods?

Parse method throws an exception if the string you are trying to parse is not a valid number whereas TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.

What is a Delegate in C#? Explain with one example.

A delegate is a type-safe function pointer that means a delegate holds the reference of a method and then calls the method for execution.

A delegate is also a user-defined type and before invoking a method using delegate we must have to define that delegate first.

Where did you use delegates in your project? Or how did you use delegates in your project?

  • These are used to represent or refer to one or more functions.
  • These can only be used to define call-back methods.
  • In order to consume a delegate, we need to create an object to delegate.
What is a Nested Type in C#?

A type (class or a struct) defined inside another class or struct is called a nested type.

What is the difference between Process and Thread?

A process is started when you start an Application. The process is a collection of resources like virtual address space, code, security contexts, etc. A process can start multiple threads. Every process starts with a single thread called primary thread. You can create n number of threads in a process. Threads share the resources allocated to the process. A process is the parent and threads are his children.

Thread – A Thread is a lightweight process that is responsible for executing application code. A process has at least one thread which is commonly called the main thread which actually executes the application code. A single process can have multiple threads.

Why we need Multi-threading in our project?

Multi-threading is used to run multiple threads simultaneously. Some main advantages are:

  1. You can do multiple tasks simultaneously. For e.g. saving the details of the user to a file while at the same time retrieving something from a web service.
  2. Threads are much lightweight than process. They don’t get their own resources. They used the resources allocated to a process.
  3. Context-switch between threads takes less time than process.
What are the advantages and disadvantages of multithreading?

Advantages of multithreading:

  1. To maintain a responsive user interface
  2. It makes the efficient use of processor time while waiting for I/O operations to complete.
  3. To split large, CPU-bound tasks to be processed simultaneously on a machine that has multiple CPUs/cores. 

Disadvantages of multithreading:

  1. On a single-core/processor machine threading can affect performance negatively as there is overhead involved with context-switching.
  2. Have to write more lines of code to accomplish the same task.
  3. Multithreaded applications are difficult to write, understand, debug and maintain.
Why does a delegate need to be passed as a parameter to the Thread class constructor?

As we know the purpose of creating a Thread is to execute a function. We also know that a delegate is a type-safe function pointer meaning it points to a function that the thread has to execute. In short, all threads require an entry point to start execution. Any thread that we create will need an explicitly defined entry point i.e. a pointer to the function from where they should begin execution. So threads always require a delegate.

What are Interlocked functions?

Interlocked functions in .NET are useful in multithreading programs to safely change the value of shared variables. By default, C# variables are not thread-safe. When we apply addition, subtraction or checking the value of variables multiple threads can corrupt the variables. For preventing these dirty reads, we can use Interlocked functions.

Interlocked functions can only work on int, long, double and float data types

What is Lock?

Lock needs an object to continue its operation. It applies a lock on a target object and only one thread can lock that target object at a time

What is the Difference between Monitor and lock in C#?

  1. The Lock is just a shortcut for Monitor statement. Compiler internally converts lock statement to Monitor.Enter and Exit statements.
  2. Monitor class provides some useful method which is not in lock statement. These methods are very useful in advanced scenarios.
  3. The monitor provides TryEnter method. This method is useful when we need to provide a timeout value.
  4. TryEnter is also useful when we have to check whether the lock is taken or not. We can pass a boolean parameter which returns true if the lock is taken else returns false.
  5. The Pulse method notifies a waiting thread of a change in the locked object’s state.
  6. Wait method releases the current acquired lock and blocks the current thread until it reacquires the lock.

Both Monitor class and lock provides a mechanism to protect the shared resources in a multithreaded application. The lock is the shortcut for Monitor.Enter with the try and finally. 

How to resolve a deadlock in a multithreaded program?

There are several techniques to avoid and resolve deadlocks. For example

  1. Acquiring locks in a specific defined order
  2. Mutex class
  3. Monitor.TryEnter() method 
  4. https://dotnettutorials.net/lesson/multi-threading-deadlock-interview-questions-answers/
What is Exception Handling in C#?

This is one of the frequently asked Exception Handling Interview Questions in C#.

The process of catching the exception for converting CLR given exception message to end-user understandable message or for stopping the abnormal termination of the program whenever runtime errors are occurring is called exception handling. Once we handle an exception under a program we will be getting following advantages

  1. We can stop the abnormal termination
  2. We can perform any corrective action that may resolve the problem occurring due to abnormal termination.
  3. Displaying a user-friendly error message, so that the client can resolve the problem provided if it is under his control.
How can we handle the exception in .NET?

There are three methods to handle the exception in .NET

  1. Logical implementation
  2. Try catch implementation
  3. On error go to implementation
Explain the difference between Error and Exception in C#?

Exceptions are those which can be handled at the runtime whereas Errors cannot be handled.

An exception is an object of a type deriving from the System.Exception class. The exception is thrown by the CLR (Common Language Runtime) when errors occur that are nonfatal and recoverable by user programs. It is meant to give you an opportunity to do something with a throw statement to transfer control to a catch clause in a try block.

The error is something that most of the time we cannot handle it. Errors are the unchecked exception and the developer is not required to do anything with these. Errors normally tend to signal the end of our program, it typically cannot be recovered from and should cause us to exit from the current program. It should not be caught or handled.

All the Errors are Exceptions but the reverse is not true. In general, Errors are which nobody can control or guess when it happened on the other hand Exception can be guessed and can be handled.

What happens if the finally block throws an exception?

The exception propagates up and should be handled at a higher level. If the exception is not handled at a higher level, the application crashes. The “finally” block execution stops at the point where the exception is thrown. 

In the example below, notice that the “finally” block in the “Hello()” method throws an exception. Hello() method is being called in the Main() method and we don’t have any exception handling mechanism in place in the Main() method. So, the application crashes with the exception.

public class Program
{
    public static void Main()
    {
        Hello();
    }

    public static void Hello()
    {
        try
        {
            // Some code
        }
        catch
        {
            // Some code
        }
        finally
        {
            Console.WriteLine("This line will be executed");
            int result = Convert.ToInt32("TEN");
            Console.WriteLine("This line will NOT be executed");
        }
    }
}

On the other hand, if you include exception handling mechanism(try/catch) in the Main() method, then you will have the opportunity to handle the exception.

public static void Main()
{
    try
    {
        Hello();
    }
    catch (Exception ex)
    {
        // Process and log the exception
        Console.WriteLine(ex.Message);
    }
}
What is the difference between the “throw” and “throw ex” in .NET?

throw : If we use “throw” statement, it preserve original error stack information. In exception handling “throw” with empty parameter is also called re-throwing the last exception.

throw ex : If we use “throw ex” statement, stack trace of exception will be replaced with a stack trace starting at the re-throw point. It is used to intentionally hide stack trace information.

  1. catch (Exception ex)   
  2. {  
  3.     // do some stuff here  
  4.     throw; // a) continue ex   
  5.     throw new MyException(“failed”, ex); // b) wrap  
  6.     throw new MyException(“failed”); // c)  replace  
  7.     throw ex; // d)  reset stack-trace  
  8. }

So it is good practice to use the “throw” statement, rather than “throw ex” because it will give us more accurate stack information rather than “throw ex”.

try
{
    // do some operation that can fail
}
catch (Exception ex)
{
    // do some local cleanup
    throw;
}

//Throw ex Syntax:
try
{
    // do some operation that can fail
}
catch (Exception ex)
{
    // do some local cleanup
    throw ex;
} 

How will you differentiate between a Class and a Struct?

ClassStructure
It is a reference data type and uses the keyword “class”.It is a value data type and uses the keyword “struct”.
Object for a class is created in the heap memory.Object for a structure is created in the stack memory.
We can always inherit another class. i.e., the concept of inheritance is applied .Structures can never be inherited.
Object is created using the “new” keyword.We may or may not use the keyword “new” while creating objects.
It occupies more space.A structure occupies less space.
Class allows both the parameterized and the non parameterized constructors.It only allows for the parameterized constructors, even the default constructors cannot be used.
Example:class fruits
{Fruit F1;F1.apple= “red”;F1.mango=”yellow”;}
Example:public struct fruit{public string apple;public string mango;}

CIL (Common Intermediate Language) or MSIL

▪ CIL or MSIL (Microsoft Intermediate Language) is the intermediate language, developed by Microsoft Corporation, for .NET.
▪ The .net programs are converted into “MSIL language” first; and then converted into “native machine language”.
▪ The MSIL code will be stored in “EXE” file. Ex: filename.exe. The “native machine language” code will not be saved in any file, it directly runs.
▪ Once the code is converted into MSIL, it doesn’t matter in which .net language it is originally developed. So for all .net languages, we can have a common runtime engine called “CLR”.

CLR (Common Language Runtime)

▪ CLR is the “Execution Engine” or “Execution Environment” of .NET.
▪ To run any type of .net program (app), CLR must be installed in the computer.
▪ CLR will be started automatically when the .net application execution starts. CLR performs essential tasks internally, while running any .net application.
▪ CLR reads the “MSIL code” from the EXE file, converts the same into “native machine code”, gives the same to the operating system and then operating system executes the native machine code; then the user gets the output. So CLR is helps the operating system while executing the .net program.
▪ CLR will be installed automatically as a part of “.NET Framework” software. CLR must be installed in both developer’s machine and user’s machine.

Sub Components of CLR

  1. Memory Manager: Which allocates memory (in RAM) for the variables and objects in the program.
  2. Garbage Collector: Which deletes the variables and objects that are created during the program, automatically at the end of the program execution.
  3. Class Loader: Which loads a class on-demand. When we try to access a class in the program for the first time, then the “Class Loader” searches for the class in the entire program, loads the class into the memory, and it passes the class to JIT compiler. That means if we don’t call a class, it will not be loaded into memory. This avoids un-necessary loading of the classes, if we don’t require them. So it improves performance.
  4. JIT (Just-In-Time) Compiler: Which converts the “MSIL code” into “native machine language” (based on current operating system).
  5. Thread Manager: Which manages the threads of the program. It gives necessary instructions to the processor, which thread is to be executed when. A thread is a “part of the program” or “background work”.
  6. Exception Manager: Which passes necessary instructions to the operating system, which code should be executed when an exception (runtime error) occurs while executing the program.
  7. Security Manager:Which takes care about different types of security in .net such as windows authentication, forms authentication, open authentication etc.

What is .NET Framework

It is the “Software Development Kit (SDK)”, which contains many components such as CIL, CLR, FCL, CLS, which is used to develop & run the .net applications.

CLS (Common Language Specification)

▪ “CLS” is the set of rules, based on which all .net languages (C#.NET, VB.NET, VC++.NET etc.) are developed.
▪ The common rules are about literals, operators, identifiers, data types, type conversion, object oriented programming etc.

CTS (Common Type System)

▪ “CTS” is a set common data types, based on which, the data types of all .net languages (C#.NET, VB.NET, VC++.NET etc.) are developed.
▪ Thus, we achieve the uniform data types among all .net languages.
▪ The following is the list of data types of CTS: SByte ,Byte,Short ,UShort, Int32 , UInt32 , Int64 , UInt64 ,Single ,Double , Decimal , Char , String , Boolean

FCL (Framework Class Library)

▪ .NET provides a set of classes and interfaces, based on which we can develop .net applications.
▪ The “DLL (Dynamic Link Library)” file is a collection of namespaces; Namespace is a collection of classes and interfaces.
▪ FCL is divided into the following parts:

  1. BCL: BCL is a set of classes and interfaces, which can be used in all types of applications.
  2. WinForms: This is a set of classes and interfaces, which can be used only in windows applications.
  3. ASP.NET: This is a set of classes and interfaces, which can be used only in web applications.
  4. ADO.NET: This is a set of classes and interfaces, which can be used in all types of applications for connecting to databases.

Naming Conventions for Identifiers

• Property names: PascalCasing
• Public Fields: PascalCasing
• Local variables: camelCasing
• Private Fields: camelCasing with underscore ( _ )

dentifiers – Any user-defined names: abc

Advantages of OOP:

  1. Modularity: Dividing large programs into multiple parts called classes.
  2. Re-usability: The class created once can be called many times.
  3. Security: The members of a class can be private or public. The private members can’t be accessible outside the class.

Object

• An object represents a real world item. For example,
you are an object,
your laptop is an object,
and your city is an object.
• An object consists of “details” and “functionality“.
• Details are called as “fields“.
• Functionality is called as “functions” or “methods” or “operations“.
• All the objects will be stored in an area called “heap” in RAM.

Class

A class is a “model” or “type” or “blue-print” of object.
• Class is used to define the common members of similar objects.
-> For example, there are 10 students. Each student is an object. So 10 students are 10 objects. In each student, we want to store “studentid”, “studentname”, “marks”. So first we have to create a class called “Student” and we have to create “studentid”, “studentname”, “marks” as members of the “Student” class. Then we have to create objects based on the class.
• A class specifies the list of Fields and methods that you want to store in every object.
• For a class, memory will not be allocated,So you must create an object for the class, in order to access its members.
Class is a just “model” only; no actual data will be stored in class. Object is the “real instance”; actual data will be stored in object only.
• When an object is created, the following process happens.

  1. Memory will be allocated in RAM (Random Access Memory) for the object.
  2. All the Fields of the class will be stored in the object.
  3. Fields of the object will be initialized with default values.
    ▪ Numerical Fields: 0
    ▪ Char / string: null
    ▪ Bool: false
    ▪ DateTime: 1/1/0001 12:00:00 AM
  4. Constructor will be called. Constructors will be explained later in this book.
    • All the objects are stored in RAM (temporarily). Objects are created when the program execution starts. Objects are automatically deleted (erased from memory) when the program execution ends.
    Each object’s memory will be allocated separately in RAM.

Principles of OOP

Encapsulation:

https://www.guru99.com/java-oops-encapsulation.html

• Encapsulation is a concept of combining Fields and methods as a single unit called “object”.
• Fields are variables that stores the data; Methods are functions that manipulates the data.
• Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.. In this, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared.

Now, let’s take the example of a medical capsule, where the drug is always safe inside the capsule. Similarly, through encapsulation, the methods and variables of a class are well hidden and safe.

Encapsulation can be achieved by:

  • Declaring the variables of a class as private.
  • Providing public setter and getter methods to modify and view the variables values.
public class Student 
{
   private String name;
   public String getName() {return name;}
   public void setName(String name) 
   {this.name = name;} 
}
class Test 
{
public static void main(String[] args) 
{
Student s=new Student();
s.setName("Harry Potter");
System.out.println(s.getName());
}
}

Now, let’s look at the code to get a better understanding of encapsulation:

As you can see in the above code, I have created a class Student which has a private variable nameNext, I have created a getter and setter to get and set the name of a student. With the help of these methods, any class which wishes to access the name variable has to do it using these getter and setter methods. 

Now let’s see one more example and understand Encapsulation in depth. In this example, the Car class has two fields –name and topSpeed. Here, both are declared as private, meaning they can not be accessed directly outside the class. We have some getter and setter methods like getName, setName, setTopSpeed etc., and they are declared as public. These methods are exposed to “outsiders” and can be used to change and retrieve data from the Car object. We have one method to set the top speed of the vehicle and two getter methods to retrieve the max speed value either in MPH or KMHt. So basically, this is what encapsulation does – it hides the implementation and gives us the values we want. Now, let’s look at the code below.

public class Car
{
private String name;
private double topSpeed;
public Car() 
{}
public String getName()
{return name; }
public void setName(String name)
{this.name= name;}
public void setTopSpeed(double speedMPH)
{topSpeed = speedMPH;}
public double getTopSpeedMPH()
{return topSpeed;}    
public double getTopSpeedKMH()
{return topSpeed*1.609344;   }
}

Here, the main program creates a Car object with a given name and uses the setter method to store the top speed for this instance. By doing this, we can easily get the speed in MPH or KMH without caring about how speed is converted in the Car class.

public class Example
{
public static void main(String args[])
Car car =new Car();
car.setName("Mustang GT 4.8-litre V8");
car.setTopSpeed(201);
System.out.println(car.getName()+ " top speed in MPH is " + car.getTopSpeedMPH());

System.out.println(car.getName() + " top speed in KMH is " + car.getTopSpeedKMH());
}

Why we need Encapsulation

Encapsulation is essential because:

  • It controls the way of data accessibility
  • Modifies the code based on the requisites
  • Helps us to achieve a loose couple
  • Achieves simplicity of our application
  • It also allows you to change the part of the code without disrupting any other functions or code present in the program

Now, let’s consider a small example that illustrates the need for encapsulation.

In the above example, it contains two instance variables as access modifier. So any class within the same package can assign and change values of those variables by creating an object of that class. Thus, we don’t have control over the values stored in the Student class as variables. In order to solve this problem, we encapsulate the Student class.

class Student 
{int id;
 String name;
} 
public class Demo 
{
public static void main(String[] args) 
{Student s = new Student();
 s.id = 0;s.name="";s.name=null;
}}

So, these were the few pointers that depict the need of Encapsulation. Now, let’s see some benefits of encapsulation.

Benefits of Encapsulation

  • Data Hiding: Here, a user will have no idea about the inner implementation of the class. Even user will not be aware of how the class is storing values in the variables. He/she will only be aware that we are passing the values to a setter method and variables are getting initialized with that value.
  • Increased Flexibility: Here, we can make the variables of the class as read-only or write-only depending on our requirement. In case you wish to make the variables as read-only then we have to omit the setter methods like setName(), setAge() etc. or if we wish to make the variables as write-only then we have to omit the get methods like getName(), getAge() etc. from the above program.
  • Reusability: It also improves the re-usability and easy to change with new requirements.

A Real-Time Example of Encapsulation

Let’s consider a television example and understand how internal implementation details are hidden from the outside class. Basically, in this example, we are hiding inner code data i.e. circuits from the external world by the cover. this can be achieved with the help of access modifiers. Access modifiers set the access or level of a class, constructors variables etc. As you can see in the below code,  I have used private access modifier to restrict the access level of the class. Variables declared as private are accessible only within Television class.

public class Television{
private double width;
private double height;
private double Screensize;
private int maxVolume;
print int volume;
private boolean power;
public Television(double width, double height, double screenSize)
{this.width=width;
this.height=height;
this.screenSize=ScreenSize;
}
public double channelTuning(int channel)
{
switch(channel)
{case1: return 34.56;
case2: return 54.89;
case3: return 73.89;
case1: return 94.98;}
return 0;
}

public int decreaseVolume()
{if(0<volume) volume --;
return volume;}
public void powerSwitch()
{this.power=!power;}
public int increaseVolume()
{if(maxVolume>volume) volume++;return volume;}}
class test{
public static void main(String args[])
{Television t= new Television(11.5,7,9);
t.powerSwitch();
t.channelTuning(2);
t.decreaseVolume();
t.increaseVolume();
television.width=12; // Throws error as variable is private and cannot be accessed outside the class}}

In the above example, I have declared all the variables as private and methods, constructors and class as public. Here, constructors, methods can be accessed outside the class. When I create an object of Television class, it can access the methods and constructors present in the class, whereas variables declared with private access modifier are hidden. That’s why when you try to access width variable in the above example, it throws an error. That’s how internal implementation details are hidden from the other classes. This is how Encapsulation is achieved .

Abstraction :

• Abstraction is a concept of hiding implementation details (internal logic) and
providing only necessary details to other classes.
• This is implemented by creating private Fields and public methods.

Abstraction is nothing but the quality of dealing with ideas rather than events. It basically deals with hiding the internal details and showing the essential things to the user.

The word abstract means a concept or an idea not associated with any specific instance.

When ? – Abstraction is needed when we need to only inherit from a certain class, but do not need to instantiate objects of that class. In such a case the base class can be regarded as “Incomplete”. Such classes are known as an “Abstract Base Class”. 

In Abstraction, by using access modifiers we can hide the required details of the object and expose only necessary methods and properties through the reference of an object.

In real-time, the laptop is a perfect example of abstraction in c#. A laptop that consists of many things such as processor, RAM, motherboard, LCD screen, camera, USB ports, battery, speakers, etc. To use it, we just need to know how to operate the laptop by switching it on, we don’t need to know how internally all the parts are working. Here, the laptop is an object which is designed to expose only required features by hiding its implementation details.

using System;
using System.Text;
namespace Tutlane
{
public class Laptop
{
private string brand;
private string model;
public string Brand
{ get { return brand; }
set { brand = value; }
}
public string Model
{
get { return model; }
set { model = value; }
}
public void LaptopDetails()
{
Console.WriteLine(“Brand: ” + Brand);
Console.WriteLine(“Model: ” + Model);
}
public void LaptopKeyboard()
{
Console.WriteLine(“Type using Keyword”);
}
private void MotherBoardInfo()
{
Console.WriteLine(“MotheBoard Information”);
}
private void InternalProcessor()
{
Console.WriteLine(“Processor Information”);
}
}
class Program
{
static void Main(string[] args)
{
Laptop l = new Laptop();
l.Brand = “Dell”;
l.Model = “Inspiron 14R”;
l.LaptopDetails();
Console.WriteLine(“\nPress Enter Key to Exit..”);
Console.ReadLine();
}
}
}

Why And When To Use Abstract Classes and Methods? – To achieve security – hide certain details and only show the important details of an object.

Calling - Java Abstraction -Edureka

If you look at the above gif, you can see when you get a call, we get an option to either pick it up or just reject it. But in reality, there is a lot of code that runs in the background. So here, you don’t know the internal processing of how a call is generated, that’s the beauty of abstraction.

You can achieve abstraction in two ways:

a) Abstract Class
b) Interface

Difference between Abstraction and Encapsulation

Abstraction hides details at the design level, while Encapsulation hides details at the implementation level.

  • Encapsulation is more about “How” to achieve a functionality
  • Abstraction is more about “What” a class can do.

1) Abstraction solves the problem at design level while Encapsulation solves its implementation level.

2) Abstraction is about hiding unwanted details while giving out the most essential details, while Encapsulation means hiding the code and data into a single unit e.g. class or method to protect the inner working of an object from the outside world. In other words, Abstraction means extracting common details or generalizing things.

3) Abstraction lets you focus on what the object does instead of how it does, while Encapsulation means hiding the internal details of how an object works. When you keep internal working details private, you can change it later with a better method.

4) Abstraction focus on outer lookout e.g. moving of vehicle while Encapsulation focuses on internal working or inner lookout e.g. how exactly the vehicle moves.

5) Abstraction is supported using interface and abstract class while Encapsulation is supported using access modifiers e.g. public, private and protected

Difference between Abstract Class and Interface

Abstract ClassInterface
An abstract class can have both abstract and non-abstract methods.The interface can have only abstract methods.
It does not support multiple inheritances.It supports multiple inheritances.
It can provide the implementation of the interface.It can not provide the implementation of the abstract class.
An abstract class can have protected and abstract public methods.An interface can have only have public abstract methods.
An abstract class can have final, static, or static final variable with any access specifier.The interface can only have a public static final variable.
https://www.youtube.com/watch?v=DMEyAYQ6Gks

What is Abstract Class?

ABSTRACT CLASS is a type of class in OOPs, that declare one or more abstract methods. These classes can have abstract methods as well as concrete methods. A normal class cannot have abstract methods. An abstract class is a class that contains at least one abstract method.

What are Abstract Methods?

ABSTRACT METHOD is a method that has just the method definition but does not contain implementation. A method without a body is known as an Abstract Method. It must be declared in an abstract class. The abstract method will never be final because the abstract class must implement all the abstract methods.

Advantages of Abstraction

  • The main benefit of using an abstract class is that it allows you to group several related classes as siblings.
  • Abstraction helps to reduce the complexity of the design and implementation process of software.

When to use Abstract Methods & Abstract Class?

Abstract methods are mostly declared where two or more subclasses are also doing the same thing in different ways through different implementations. It also extends the same Abstract class and offers different implementations of the abstract methods.

Abstract classes help to describe generic types of behaviors and object-oriented programming class hierarchy. It also describes subclasses to offer implementation details of the abstract class.

Summary:

  • Abstraction is the process of selecting important data sets for an Object in your software and leaving out the insignificant ones.
  • Once you have modelled your object using Abstraction, the same set of data could be used in different applications

Inheritance :

-Inheritance is a concept of creating “parent-child” relationship among two or more classes.
-As a result of inheritance, all the members of parent class are accessible in child class

Polymorphism :-

– The name means, one name, many forms. It is achieved by having multiple methods with the same name but different implementations.
– The ability of an entity to take several forms. In other words, it refers to the ability of an object (or a reference to an object) to take different forms of objects. It allows a common data-gathering message to be sent to each class.
– Polymorphism encourages called as ‘extendibility’ which means an object or a class can have it’s uses extended

  • Man is only one, but he takes multiple roles like – he is a dad to his child, he is an employee, a salesperson and many more. This is known as Polymorphism
Consider a cell phone where you save your Contacts. Suppose a person has two contact numbers. For the ease of accessibility, your cellphone provides you the functionality where you can save two numbers under the same name. This is also known as Method Overloading.

https://www.edureka.co/blog/polymorphism-in-java/#WhatisPolymorphism

Now let’s take another example and understand polymorphism in depth. Suppose you went to a Shopping Centre (Allen Solly) near your home and bought a pair of jeans. A week later, while traveling to a nearby town, you spot another Shopping center. You walk into the shop and find a new variant of the same brand which you liked even more. But you decided to buy it from the shop near to your home. Once back home, you again went to the Shopping Center near your home to get those amazing pair of Jeans but couldn’t find it. Why? Because that was a specialty of the shop that was located in the neighboring town. 

Now relating this concept to an object-oriented language like Java, suppose you have a class named XJeans which includes a method named jeans(). Using this method, you can get an Allen Solly jeans. For the Jeans in the neighboring town, there is another class YJeans. Both the classes XJeans and YJeans extends the parent class ABCShoppingCenter. The YJeans class includes a method named jeans(), using which you can get both the jeans variants.

class ABCShoppingCenter {
public void jeans() {
System.out.println("Default AllenSolly Jeans");
}}
class XJeans extends ABCShoppingCenter
{
public void jeans()
{
System.out.println("Default AllenSolly Jeans");
}}
class YJeans extends ABCShoppingCenter
{ // This is overridden method
public void jeans()
{System.out.println("New variant of AllenSolly");
} }
So, instead of creating different methods for every new variant, we can have a single method jeans(), which can be defined as per the different child classes. Thus, the method named jeans() has two definitions – one with only default jeans and other with both, the default jeans and the new variant. Now, which method gets invoked will depend on the type of object it belongs to. If you create ABCShoppingCenter class object, then there will be only one jeans available. But if you create YJeans class object, that extends ABCShoppingCenter class, then you can have both the variants. This is also known as Method Overriding. 

Thus, Polymorphism increases the simplicity and readability of the code by reducing the complexity. This makes Polymorphism in Java a very useful concept and it can be applied in real-world scenarios as well.

Virtual methods

– The main objective of virtual method is that, you can redefine it in one or more derived classes. You can use virtual keyword with method, property, indexer, or event.
– It allows these members to be overridden in a derived class. The implementation of a virtual member can be changed in a derived class by overriding these members (method, property, indexer, event).
– The process of redefining a virtual method in a derived class is called method overriding.
– It is also called as runtime polymorphism, late binding or dynamic binding.
– When overriding a method, the name, return type, and signature of the overriding method should be the same as the virtual method.

It is not compulsory to override a virtual method in derived class. In multilevel hierarchy if a derived class does not provide its own version of a virtual method, then the one in the base class is used.

Example

using System;
namespace ConsoleApplication1
{
     class BaseClass
    {       
        public virtual void show()
        {
            Console.WriteLine(“Base class method is called”);
        }
    }
    class DerivedClass : BaseClass
    {        
         public override void show()
        {
            Console.WriteLine(“DerivedClass method is called”);
        }
    }
    class MostDerivedClass : DerivedClass
    {
         public override void show()
        {
            Console.WriteLine(“MostDerivedClass  method is called”);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            BaseClass baseObj;
            MostDerivedClass obj = new MostDerivedClass();
            obj.show();
            baseObj = obj;
            baseObj.show();
            Console.ReadLine();
        }
    }
}
Output:
MostDerivedClass method is called
MostDerivedClass method is called

The above program creates a base class called BaseClass and two derived classes, called DerivedClass and MostDerivedClassBaseClass have a method called show( ), and both the derived classes override it. Inside the Main( ) method, we have created two objects of type BaseClass (reference) and MostDerivedClass.

Please see the output carefully. You can call the derived class method by using reference of base class. It is main advantage of virtual and overriding (Run time binding).

Understanding virtual, override and new keyword in C#

-The override modifier extends the base class virtual method
-The new modifier hides an accessible base class method

Polymorphism is one one of the main aspect of OOPS Principles which include method overriding and method overloading. Virtual and Override keyword are used for method overriding and new keyword is used for method hiding. In this article, In this article, I am going to explain each keyword in details with the help of C# code.

Method Overloading, Overriding and Hiding
https://www.dotnettricks.com/learn/csharp/understanding-virtual-override-and-new-keyword-in-csharp

Singleton Vs Static Classes

Static and Singleton are very different in their usage and implementation. So we need to wisely choose either of these two in our projects.

— The word “single” means single object across the application life cycle, so the scope is at application level.
– The static does not have any Object pointer, so the scope is at App Domain level.

Singleton is a pattern and not a keyword. A singleton allows a class for which there is just one, persistent instance across the lifetime of an application. That means, it created a single instance and that instance (reference to that instance) can be passed as a parameter to other methods, and treated as a normal object. While a static class allows only static methods and you cannot pass static class as parameter

A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state

A Singleton can be initialized lazily or asynchronously and loaded automatically by the .NET Framework CLR (common language runtime) when the program or namespace containing the class is loaded. While a static class is generally initialized when it is first loaded and it will lead to potential class loader issues.

Singleton class follow the Object Oriented Principles, so that singletons can be handled polymorphically without forcing their users to assume that there is only one instance. While static cannot.

  1. Singleton Objects stored on heap while static class stored in stack.
  2. Singleton Objects can have constructor while Static Class cannot.
  3. Singleton Objects can dispose but not static class.
  4. Singleton Objects can clone but not with static class.

Difference between Properties and Fields

-Clearly both will expose an object’s state to the outside world.
-Data hiding is the key term describing an Object Oriented Language. That means the internal working of a class should be hidden from the outside world. So, If you expose a member field you are actually exposing the internal implementation of the class.
– Therefore we wrap fields with Properties to give us the ability to change the implementation without breaking code depending on us.

The above statements underlines that properties should be used to define a class’s public interface while fields are meant to be used in the private, internal workings of a class.

Properties vs Fields

Field

A field is a variable that is declared directly in a class or struct. Generally, developers should use fields only for variables that have private or protected accessibility. Fields should (most of the time) be kept private to a class and accessed via get and set properties.

public class TestClass
{
//Here declare a field _testField, it is private to your class and stores the actual data.
    private string _testField;
//Fields should be kept private to a class and accessed via get and set properties.
    public string TestField
    {
        get
        {
            return _testField;
        }
        set
        {
            _testField = value;
        }
    }
}

Properties

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties expose fields, that means it enable a class to expose a public way of getting and setting values, while hiding implementation.
-Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.

Indexers

An indexer is a special type of property that allows a class or a structure to be accessed like an array for its internal collection. The main difference between Indexers and Properties is that the accessors of the Indexers will take parameters.
C# allows us to define custom :
indexers,
generic indexers,
and also overload indexers.

Instances of such classes can be accessed using the [] array access operator.
-Indexers are commonly used for classes, which represents some data structure, an array, list, map and so on.

Random order access– You would use an enumerator if your data is normally accessed sequentially.
-An indexer on the other hand is useful for directly accessing a specific element, no specific order.

This of course assumes you know the index of the element you want. Comboboxes for example have always supported two values: the string shown to the user, and the id that belongs with it. You could use the id from a selected item in a combobox to directly access the index of your collection, instead of having to search the collection.

The nice thing about indexers in C# is that you can overload them, so you can access items through different kind of keys.

class StringDataStore
{
    private string[] strArr = new string[10]; // internal data storage

    public string this[int index]
    {
        get => strArr[index];

        set => strArr[index] = value;
    }
}
StringDataStore<string> names = new StringDataStore<string>(5);
names[0] = "Steve";
names[1] = "Bill";

Serialization (C#)

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 be able to recreate it when needed. The reverse process is called deserialization.

How serialization works

This illustration shows the overall process of serialization:

Serialization graphic

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.

Uses for serialization

Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. Through serialization, a developer 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 user-specific information across applications

Binary Serialization – Faster and demands less space; it converts any code into its binary form. Serialize and restore public and non-public properties.
SOAP – It produces a complete SOAP compliant envelope that is usable by any system capable of understanding SOAP. The classes about this type of serialization reside in System.Runtime.Serialization.
XML Serialization – Serializes all the public properties to the XML document.
In addition to being easy to read, the XML document manipulated in several formats. The classes in this type of serialization reside in System.sml.Serialization
JSON serialization -The System.Text.Json namespace contains classes for JavaScript Object Notation (JSON) serialization and deserialization. JSON is an open standard that is commonly used for sharing data across the web.

XML serialization serializes the public fields 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. XML serialization results in strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization contains classes for serializing and deserializing XML. You apply attributes to classes and class members to control the way the XmlSerializer serializes or deserializes an instance of the class.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/how-to-read-object-data-from-an-xml-file

Is it possible to use this keyword within a static method in C#?

A: A special type of reference variable, this keyword is implicitly defined with each non-static method and constructor as the first parameter of the type class, which defines it. Static methods don’t belong to a particular instance. Instead, they exist without creating an instance of the class and calls with the name of the class. Because this keyword returns a reference to the current instance of the class containing it, it can’t be used in a static method. Although we can’t use this keyword within a static
method,
we can use it in the function parameters of Extension Methods.

What do you mean by Constructor Chaining in C#?

You could say this is the art of calling constructors from other constructors in the same class or from the base class.

This is very handy when we have a class that defines multiple constructors. Assume we are developing a class Student. And this class has three constructors. On each constructer, we have to validate the student’s ID and categorize him/her. So if we do not use the constructor chaining approach, it would be something similar to what is shown below:

271582/screen_01_thumb_2_.png

Even though the above approach solves our problem, it duplicates code. (We are assigning a value to ‘_id’ in all our constructors). This is where constructor chaining is very useful. It will eliminate this problem. This time, we only assign values in one constructor which consists of the most number of parameters. And we call that constructor when the other two constructers are called.

class Student {
    string _studentType = "";
    string _id = "";
    string _fName = "";
    string _lName = "";
    public Student(string id): this(id, "", "") {
    }
    public Student(string id, string fName): this(id, fName, ""){
    }
    public Student(string id, string fName, string lName) {
        //Validate logic.....
        _studentType = "<student_type>";
        _id = id;
        _fName = fName;
        _lName = lName;
    }
}

**Please note: If you do not specify anything [in this example, we used ‘this’), it will be considered that we are calling the constructor on the base class. And it’s similar to using ‘: base(…)’].

Sealed Class in C#

https://www.interviewsansar.com/real-time-example-of-sealed-class-and-method-in-c/

Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as a sealed class, this class cannot be inherited. 

 One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.Drawing namespace.The Pens class represents the pens with standard colors. This class has only static members.

For example, Pens.Blue represents a pen with blue color. Similarly, the Brushes class represents standard brushes. The Brushes.Blue represents a brush with blue color. 

So when you’re designing a class library and want to restrict your classes not to be derived by developers, you may want to use sealed classes.

Sealed class real time example – Apartment and Flat design:

We’ll have only 1BHK, 2BHK and 3BHK flat in the Apartment. This is the constraint and more than this i.e. 4BHK or above will not be allowed in this apartment.

Second constraint is 1BHK flat will have rectangular balcony and 2BHK or above will have only circular balcony. Above 2BHK flats cannot have their own balcony design but circular only.

In this design we’ll use multilevel inheritance as some of the features of 1BHK can be inherited in 2 BHK and some 2 BHK features can be inherited in 3 BHK etc.

Use of Sealed class – Since, first constraint is that the Apartment can have only up to 3BHK flats. So, we’ll have to mark 3BHK class as sealed. So, that no further extension is possible, means we cannot create 4BHK or above in the apartment.

Use of Sealed method – As per second constraint i.e. 1 BHK has only rectangular balcony and 2BHK or above will have only circular balcony. Also note that 3BHK or above will not be allowed to have their own design (implementation) and will have circular only. means, it will inherit the balcony design of 2BHK.
Hence, we will mark balcony () method as sealed in 2BHK to prevent overriding in 3BHK or above classes.

can we create derived class object from base class c#

What is Use of Private Constructor in C# ? Scenarios Example

What are the different types of classes in C#?

Ans: The different types of class in C# are:
 Partial class – Allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.
 Sealed class – It is a class which cannot be inherited. To access the members of a sealed class, we need to create the object of the class. It is denoted by the keyword Sealed.
 Abstract class – It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method. It is denoted by the keyword abstract.
 Static class – It is a class which does not allow inheritance. The members of the class are also static. It is denoted by the keyword static. This keyword tells the compiler to check for any accidental instances of the static class.

Usage and Importance of Using in C#

There are two ways to use the using in C#. One is as a directive and the other is as a statement.

Using Directive

Generally, we use the using keyword to add namespaces in code-behind and class files. Then it makes all the classes, interfaces and abstract classes and their methods and properties available in the current page. Adding a namespace can be done in the following two ways, A. To allow the normal use of types in a namespace,

  1. using System.IO;  
  2. using System.Text;  

B. To create an alias for a namespace or a type. This is called a using alias directive. 

  1. using MyProject = TruckingApp.Services;  

We can use the namespace alias as in the following:

  1. MyProject.Truck newObj = new MyProject.Truck();  

This one (option B) is very useful when the same class/abstract/interface is present in multiple namespaces.

Let’s say the Truck class is present in TruckingApp1, TruckingApp2, and TruckingApp3. Then it is difficult to call the Truck class of namespace2.

Here the alias directive gives an elegant syntax to use the Truck class. Code

  1. using namespace1 = TruckingApp1.Services;  
  2. using namespace2 = TruckingApp2.Services;  
  3. using namespace3 = TruckingApp3.Services;  
  4. namespace2.Truck newObj = new namespace2.Truck();  

Now the code looks more elegant and easy to understand. Except for this way, you can also access the Truck class using namespace directly as in the following:

  1. TruckingApp.Services2.Truck newObj = new TruckingApp.Services2.Truck();  

This one has one disadvantage. If I am using the Truck class in 100 places, then I need to use the namespace name every time. So always use the alias directive in this scenario.

Using Statement

 It plays a vital role in improving performance in Garbage Collection. The using statement is mostly used to handle any managed object that implements the IDisposable interface.

The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom Garbage Collection. In other words, if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs, then here the using statement closes the connection automatically. here’s no need to call the connection Close() method explicitly. 

Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, and there is no need to call the Close() and Dispose() methods explicitly. For more on Connection Pooling, visit the link here.

https://www.c-sharpcorner.com/UploadFile/manas1/usage-and-importance-of-using-in-C-Sharp472/

Ref and out keywords

What is Managed and Unmanaged code?

Ans: Managed code is a code which is executed by CLR (Common Language
Runtime) i.e all application code based on .Net Platform. It is considered as managed because of the .Net framework which internally uses the garbage collector to clear up the unused memory.
Unmanaged code is any code that is executed by application runtime of any other framework apart from .Net. The application runtime will take care of memory, security and other performance operations.
A code which is directly executed by the operating system is known as Unmanaged code.
In unmanaged code, the memory allocation, type safety, security, etc are managed by the developer. Due to this, there are several problems related to memory occur like buffer overflow, memory leak, pointer override, etc. The executable files of unmanaged code are generally in binary images, x86 code which is directly loaded into memory. The application written in VB 6.0, C, C++, etc are always in unmanaged code.

What is a Destructor in C#?

Hashtable Vs Dictionary

HashtableDictionary
A Hashtable is a non-generic collection.A Dictionary is a generic collection.
Hashtable is defined under System.Collections namespace.Dictionary is defined under System.Collections.Generic namespace.
In Hashtable, you can store key/value pairs of the same type or of the different type.In Dictionary, you can store key/value pairs of same type.
In Hashtable, there is no need to specify the type of the key and value.In Dictionary, you must specify the type of key and value.
The data retrieval is slower than Dictionary due to boxing/ unboxing.The data retrieval is faster than Hashtable due to no boxing/ unboxing.
In Hashtable, if you try to access a key that doesn’t present in the given Hashtable, then it will give null values.In Dictionary, if you try to access a key that doesn’t present in the given Dictionary, then it will give error.
It is thread safe.It is also thread safe but only for public static members.
It doesn’t maintain the order of stored values.It always maintain the order of stored values.