What is difference in Boxing and Unboxing

In C#, boxing and unboxing are concepts used to convert between value types and reference types.

Boxing:
Boxing is the process of converting a value type into a reference type. This is done by wrapping the value of the value type in an object of the corresponding reference type. For example, when an integer value is boxed, it is wrapped in an object of the System.Object class. The boxed object can then be assigned to a reference type variable or passed as a parameter to a method that expects a reference type.

Unboxing:
Unboxing is the opposite of boxing, and it is the process of converting a reference type that was previously boxed back into its original value type. This is done by extracting the value from the object and assigning it to a value type variable.

Here's an example of how boxing and unboxing work in C#:

int i = 10; // Value type variable
object o = i; // Boxing: i is converted to a reference type object and assigned to o

int j = (int)o; // Unboxing: the value of o is extracted and assigned to a value type variable j

In the above example, the value of the integer variable i is boxed into an object variable o. The value is then unboxed and assigned back to an integer variable j.

It is important to note that boxing and unboxing operations can be expensive in terms of performance, especially when done repeatedly. This is because they involve the creation of new objects on the heap, which can lead to memory allocation and garbage collection overheads. Therefore, it is generally recommended to avoid boxing and unboxing operations as much as possible, and instead use generics or value types directly whenever possible.

What is Difference in Is and As Keywords in C#

As we familiar that value of any type can be treated as an object then in the code it is difficult to determine that stored value in object of which type. If we want to write a logic for specific value type then is and as both keywords help to determine the specific object type.

The is keyword used to check run-time type of an object is compatible and used to check object is type of specific object or not. The is keyword checks whether the value on its left side is a compatible instance of the type on the right side.

object obj = "Hello";

if (obj is string)  // Check whether obj contains value, compatible with right side specific type
{
     // Do Something
}

Where the as operator used to cast an object to a specific type and it returns null if not able to cast. Good to use as keyword, benefits it does not throw an exception when type casting fails.

Basically mostly the as keyword is used to cast Null-able types. If the specified value is not an instance of the specified type then null is returned always.

string str = obj as string;

if (str != null)  //  str will contain null if not string
{
     // Do Something
}

What is difference between Clustered Index and Non Clustered Index

A Table can have two type of index that is Clustered Index and Non-Clustered Index but both job is to store data in sorted order and retrieve a data faster when perform a query.

Clustered Index 

The Clustered Index determines how data is stored in physically on the table in the sorted order. Advantage of using index is to store data in table in sorted order even insertion in the table is not sorted. Default sorting of data is ascending.

A table can have only one clustered index and this is usually created by default on the primary key. A clustered index can be created for another column also if primary key is not exists on the table. 

For an Example - The primary key on EmpId column will create a clustered index for the EmpId column. A table can have only one clustered index on it.

SQL Server stores data in the table according a clustered index. It helps to make SELECT query faster. A query with index is always faster than a query without index.

getdate()
SELECT  * FROM  EMPLOYEE where EmpId = 150
getdate()

Insert some dummy data into Employee Table, Let's say 10,000 records to measure the above query execution time without index and with index on EmpId.

If no any index is added then each row will be compared to find the EmpId 150. If Clustered index is created on the table then it will give records faster from physically stored data using a search technique Binary Search Tree.

Clustered Index is slightly faster than non-clustered index.

Non-Clustered Index 

When the Non-clustered index created then It takes extra physical storage of the data in sorted order of non-clustered index column with a row pointer which points to row of actual storage data in the table. When perform a query on non-clustered index column then it do extra lookup for actual data which is stored in the table with the help of row pointer.

Non-Clustered are generally used when we want to have more than one index other than primary key constraint.

We can create a single non-clustered index for multiple columns and all columns will be sorted as specified in the index. We call it Composite Clustered Index.

The 249 Non-clustered Index can be created per table in SQL Server 2005 where SQL server 2008 can have 999 non-clustered Index per table.

On which Column we have to apply the non-Clustered Index -

  • The column used multiple time in the search criteria across.
  • The column most of the time used to join other tables.
  • The column used as Foreign Key most of the time.
  • The column used in Join, Where, and Order By clauses in most cases
4 Main Differences in Clustered Index and Non-Clustered Index

1. Only one clustered Index can be created per table where non clustered index can be created  per table more than one.
2. Clustered Index is by default unique key Index where non-clustered index can be non unique too.
3. Clustered Index are slightly faster than Non-Clustered Index.
4. Clustered Index stored sorted data with in the table itself where non-clustered index required extra disk storage to sort the data.

What is Difference in Stored Procedure and Functions

Stored Procedure and User Defined Functions both are SQL Server objects but both are much different in  implementation and usage.

Differences -
  1. Function must return something in from of single value or table but stored procedure may or may not.
  2. Function cannot have output parameter where stored procedure can have output parameter.
  3. Function must be written with single input parameter where stored procedure can be written without any parameter.
  4. Functions are usually called by a Stored Procedure where Stored Procedure cannot be call from a Function.
  5. Function cannot have try-catch block where Stored Procedure can have try-catch block and can handle exceptions. 
  6. Transaction block cannot be written in Function where in Stored Procedure it can be written.
Usage Difference -
  • To avoid a repeating code in Stored Procedure you can write a user defined function and can use this function for all stored procedures.
  • To implement a generic code can be written a function. For an example - Write a function which returns customer's Age in years base on his Date of Birth.
  • Functions used usually for returning something somewhat common. For an example - In-built SQL Function getdate() returns always today date and repeatedly called in Stored Procedure.

What is an Extension Method and When to Use it

Extension method is a feature of C# 3.0. The extension method helps to add method in existing class without modifying the source code or without inheriting the class. It achieves to add a new methods in the class even source code is not available means you had referenced the DLL of code in your project and want to add a new method into that. 

For an example - you can add a new method in existing dotnet base classes and excess the same method in your coding whenever required. You may add a new method also in your defined classes which you had created earlier and without impacting the source code of the class you want  to add a new method into that.

Extension methods are special kind of static method which must be written in static class where the first parameter helps to compiler and make clear that this class is going to be extend with a new method and this method will be accessible too through instance of extended class.

When to use Extension Method -

1. You cannot modify the source code of the class as you don't have source code. Eg - you had referenced DLLs.

2. When you don't want to modify the class as it seems to risky to modify the original class then better to add a new method in the class using a extension method.

Restriction in Implementing Extension Method -

1. When you extend a method then you had given the same name and signature which exists in extended class then it will be never called. Avoid to give the same name and signature, method signature should be identical.

2. Extension methods not meant to override the existing method. It promotes to add a new method in existing types.

3. The Fields, Properties and Events cannot be added only it supports to new methods.

4. Extension method must be static and should be written in a static class.

What is Difference in readonly and const

In C#, both readonly and const are used to declare variables that cannot be modified once they are initialized, but there are some differences between them:

Initialization:
const variables must be initialized at the time of declaration with a compile-time constant value, such as a number or a string literal. readonly variables can be initialized at the time of declaration or in a constructor of the containing class.

Scope:
const variables are implicitly static and have a global scope within the containing assembly, which means they can be accessed from any part of the code in the assembly. readonly variables can have instance-level scope and can be different for each instance of the class that contains them.

Performance:
const variables are replaced with their values at compile-time, which means they are faster to access at runtime because there is no need to look up their value in memory. readonly variables are initialized at runtime and therefore incur a slight performance overhead when accessed.

Here's an example of how const and readonly variables can be used in C#:


class MyClass
{
    public const int MyConst = 10; // Compile-time constant

    public readonly int MyReadOnly; // Readonly variable

    public MyClass(int value)
    {
        MyReadOnly = value; // Initialized in constructor
    }
}

In the above example, MyConst is a const variable that is initialized at the time of declaration with a compile-time constant value. MyReadOnly is a readonly variable that is initialized in the constructor with a value that can vary for each instance of the MyClass class.

In summary, the main differences between const and readonly variables are that const variables must be initialized with a compile-time constant value, have a global scope, and are faster to access at runtime, while readonly variables can be initialized in a constructor, have instance-level scope, and incur a slight performance overhead when accessed.


What is Difference in Value Type and Reference Type

Value Type hold actual value of data and stored in stack where reference type hold memory address of data and point to actual data and stack is used to store memory address of reference type and actual data stored into different memory that is heap.

So whenever we pass value of any value type data then the value is not changed whereas when we passing the reference type then as it is referenced to memory location of actual data then value get changed in caller method.

Generally value type are all numeric Data Types, Chars, Booleans, Enumerations and Structs whereas reference type are Classes, Strings, Arrays and Delegates.

Differences -
  • Value types are stored on stack where Reference types are stored on heap.
  • When passed as value type new memory location is created and stored the new value in this memory whereas in reference type it is pointing to same memory location and that's why passed value is get changed in memory.
  • Value type holds actual data whereas Reference type hold memory address of the data and point to actual data.
  • Value types cannot assign the value null whereas Reference types can be assigned the value null.
Example of Value type

int x=5;
int y=x;

It will create a two location of memory first with (x,5) and other one with (y,5).

Example of Reference Type

Employee e=new employee();
e.Id=101;
e.Name="Ramesh";

Employee e1=e;
e1.ID=102;
e1.Name="Rajesh";

Here e variable pointing to location of stored data on heap as (ID, Name) and when we assign e into new variable e1 then it is also pointing the same data (ID,Name).

Suppose if e has memory address 1000 and pointing to (ID,Name) of employee then e1 will also pointing the same memory address that is 1000 and will point to (ID,Name) .



What is Use of Static Class

A static class is a class that cannot be instantiated and can only contain static members such as methods, properties, fields, and events. These members are accessible through the class name rather than an instance of the class.

Here are some common use cases for static classes:

Utility Classes:
A static class can be used to create a utility class that contains a set of related methods that perform common tasks. For example, the Math class in the .NET Framework is a static class that contains a set of mathematical functions.

Extension Methods:
A static class can also be used to define extension methods that add functionality to an existing class without modifying the class itself. Extension methods must be defined in a static class.

Constants:
A static class can be used to define a set of constant values that are used throughout an application. This makes it easy to change the value of a constant in one place and have the change propagate throughout the application.

Singleton Pattern:
A static class can be used to implement the Singleton pattern, which ensures that only one instance of a class is created and provides a global point of access to that instance.

Performance:
Static methods are faster than instance methods because they don't have to create an instance of the class before invoking the method. This can be useful in performance-critical scenarios.

Here's an example of a static class:

public static class UtilityClass
{
    public static int Add(int a, int b)
    {
        return a + b;
    }

    public static string ReverseString(string s)
    {
        char[] charArray = s.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
}

In the above example, UtilityClass is a static class that contains two static methods: Add() and ReverseString(). These methods can be called directly on the class name without creating an instance of the class.

In summary, a static class in C# is a class that cannot be instantiated and contains only static members. It can be used to create utility classes, define extension methods, define constants, implement the Singleton pattern, and improve performance.