Showing posts with label CSharp. Show all posts
Showing posts with label CSharp. Show all posts

What is difference in Ref and Out Parameter

In C#, both ref and out are used to pass arguments by reference instead of by value, but there are some differences between them:

Initialization: The ref parameter must be initialized before it is passed to the method, while the out parameter does not need to be initialized. Instead, the method is responsible for assigning a value to the out parameter before returning.

Return value: A method can return a value through an out parameter, but not through a ref parameter.

Compiler error: The out parameter must be assigned a value inside the method before it returns. If it is not assigned a value, the compiler generates an error. In contrast, the ref parameter does not have to be assigned a value inside the method.

Usage: The ref parameter is used when the method needs to modify the value of the parameter that is passed in, while the out parameter is used when the method needs to return multiple values.

Examples in C#:

// using ref
void AddOne(ref int x)
{
    x += 1;
}

int number = 5;
AddOne(ref number);
Console.WriteLine(number); // output: 6

// using out
void Divide(int dividend, int divisor, out int quotient, out int remainder)
{
    quotient = dividend / divisor;
    remainder = dividend % divisor;
}

int dividend = 10;
int divisor = 3;
int quotient, remainder;
Divide(dividend, divisor, out quotient, out remainder);
Console.WriteLine($"{dividend}/{divisor} = {quotient} remainder {remainder}"); // output: 10/3 = 3 remainder 1

In the above example, ref is used to modify the value of the number parameter, while out is used to return both the quotient and remainder from the Divide method.

What is Delegate, Anonymous Method and Lambda Expression

A delegate is a type that represents a reference to a method with a specific signature. It is similar to a function pointer in C/C++. A delegate can be used to encapsulate a method call and pass it as an argument to another method or store it as a field or property. 

Here's an example:

public delegate int CalculationDelegate(int x, int y);

public class Calculator
{
    public int Add(int x, int y)
    {
        return x + y;
    }

    public int Multiply(int x, int y)
    {
        return x * y;
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        Calculator calculator = new Calculator();

        CalculationDelegate add = calculator.Add;
        int result = add(2, 3); // result = 5

        CalculationDelegate multiply = calculator.Multiply;
        result = multiply(2, 3); // result = 6
    }
}

An anonymous method is a method without a name that can be defined inline with the code using a delegate. It allows you to define a method without having to create a separate method declaration. 

Here's an example:

CalculationDelegate add = delegate (int x, int y)
{
    return x + y;
};

int result = add(2, 3); // result = 5

A lambda expression is a concise way to define an anonymous method. It is a shorthand notation that allows you to define a method inline with the code using the => operator. Lambda expressions are typically used with delegates, but they can also be used with other types that define a single method, such as Func and Action. 

Here's an example:

CalculationDelegate add = (x, y) => x + y;

int result = add(2, 3); // result = 5

Lambda expressions are often used with LINQ queries, which use functional programming techniques to filter, sort, and transform data.




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