Sunday, 21 July 2024

Var vs Dynamic Variables in C#

 

var vs dynamic in C#

Explanation

In C#, var and dynamic are both used for variable declaration but serve different purposes and have distinct behaviors.

var

The var keyword is used for implicit type declaration. When you declare a variable using var, the compiler infers the type of the variable from the expression on the right-hand side of the assignment. The type is determined at compile-time and cannot change.

Key Characteristics of var:

  • Type is determined at compile-time.
  • Strongly typed: once the type is inferred, it cannot be changed.
  • Useful for simplifying code and avoiding redundancy when the type is evident from the right-hand side of the assignment.






Advantages of var:

  • Reduces code verbosity.
  • Enhances readability when the type is obvious.
  • Avoids repetition of type names.

Limitations of var:

  • The type must be determinable by the compiler.
  • Cannot be used when the right-hand side does not provide enough information for type inference (e.g., when the right-hand side is null).

dynamic

The dynamic keyword is used to declare variables that are resolved at runtime. This means the type of the variable is determined during execution, and type-checking is deferred until the variable is used.

Key Characteristics of dynamic:

  • Type is determined at runtime.
  • Allows for dynamic typing: the type can change, and any member can be accessed.
  • Useful for scenarios involving reflection, COM interop, or dynamic languages integration.








Advantages of dynamic:

  • Flexibility in handling types that are not known at compile-time.
  • Simplifies code that involves reflection, dynamic languages, or late-binding scenarios.

Limitations of dynamic:

  • No compile-time type checking: errors related to type mismatch or missing members are only caught at runtime.
  • Performance overhead due to runtime type resolution.
  • Potentially less readable and maintainable code due to lack of type information.

 

Comparison

Feature

var

dynamic

Type Determination

Compile-time

Runtime

Type Checking

Compile-time

Runtime

Type Safety

Strongly typed

Weakly typed

Use Cases

Clear and specific type

Unknown type, dynamic scenarios

Performance

No overhead

Runtime overhead

Error Checking

Caught at compile-time

Caught at runtime








Summary

  • Use var when you want the compiler to infer the type and benefit from compile-time type checking and performance.
  • Use dynamic when you need flexibility with types that are determined at runtime and can handle the potential runtime errors and performance overhead.

If block in c#

 ## C# `if` and `else` Conditional Statements


### Explanation


Conditional statements in C# allow you to execute certain blocks of code based on whether a condition is true or false. The most common conditional statements are `if` and `else`.


### Theory


#### `if` Statement


An `if` statement evaluates a boolean expression and executes a block of code if the expression is true. The syntax is:


```csharp

if (condition)

{

    // Code to be executed if condition is true

}

```


#### `else` Statement


An `else` statement follows an `if` statement and executes a block of code if the `if` condition is false. The syntax is:


```csharp

if (condition)

{

    // Code to be executed if condition is true

}

else

{

    // Code to be executed if condition is false

}

```


#### `else if` Statement


An `else if` statement allows you to check multiple conditions. If the initial `if` condition is false, the `else if` condition is evaluated. The syntax is:


```csharp

if (condition1)

{

    // Code to be executed if condition1 is true

}

else if (condition2)

{

    // Code to be executed if condition2 is true

}

else

{

    // Code to be executed if both condition1 and condition2 are false

}

```


### Diagram


Here is a flowchart representing the `if-else` structure:


```

            +------------------+

            |   Condition 1    |

            +------------------+

                     |

          +----------+----------+

          | true                 | false

          v                      v

   +---------------+     +------------------+

   |  Execute Code |     |   Condition 2    |

   +---------------+     +------------------+

                                |

                     +----------+----------+

                     | true                 | false

                     v                      v

              +---------------+     +----------------+

              |  Execute Code |     |  Execute Code  |

              +---------------+     +----------------+

```


### Examples


#### Example 1: Checking a Number


Here is an example of an `if-else` statement in C# that checks if a number is positive, negative, or zero:


```csharp

using System;


class Program

{

    static void Main()

    {

        int number = 10;


        if (number > 0)

        {

            Console.WriteLine("The number is positive.");

        }

        else if (number < 0)

        {

            Console.WriteLine("The number is negative.");

        }

        else

        {

            Console.WriteLine("The number is zero.");

        }

    }

}

```


**Output**:

```

The number is positive.

```


#### Example 2: Checking User Input


Here is an example of using `if-else` statements to validate user input:


```csharp

using System;


class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        string input = Console.ReadLine();

        int number;


        if (int.TryParse(input, out number))

        {

            if (number % 2 == 0)

            {

                Console.WriteLine("The number is even.");

            }

            else

            {

                Console.WriteLine("The number is odd.");

            }

        }

        else

        {

            Console.WriteLine("Invalid input.");

        }

    }

}

```


**Output** (Example 1):

```

Enter a number: 4

The number is even.

```


**Output** (Example 2):

```

Enter a number: hello

Invalid input.

```


#### Example 3: Grading System


Here is an example of using `if-else` statements to determine the grade based on a score:


```csharp

using System;


class Program

{

    static void Main()

    {

        int score = 85;


        if (score >= 90)

        {

            Console.WriteLine("Grade: A");

        }

        else if (score >= 80)

        {

            Console.WriteLine("Grade: B");

        }

        else if (score >= 70)

        {

            Console.WriteLine("Grade: C");

        }

        else if (score >= 60)

        {

            Console.WriteLine("Grade: D");

        }

        else

        {

            Console.WriteLine("Grade: F");

        }

    }

}

```


**Output**:

```

Grade: B

```


### Summary


Conditional statements using `if` and `else` in C# are essential for controlling the flow of a program based on specific conditions. They allow for decision-making processes within your code, enabling different outcomes based on varying conditions. This is fundamental for creating dynamic and responsive applications.

While Loop in C#

 ## C# `while` Loop: Explanation, Theory, and Examples


### Explanation


A `while` loop in C# is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The loop continues to execute as long as the condition remains true.


### Theory


The `while` loop consists of two main parts:

1. **Condition**: This boolean expression is evaluated before each iteration of the loop. If the condition is true, the loop body is executed; if false, the loop terminates.

2. **Loop Body**: This is the block of code that is executed repeatedly as long as the condition is true.


The basic syntax of a `while` loop in C# is:


```csharp

while (condition)

{

    // Code to be executed

}

```


### Diagram


Here is a flowchart representing the C# `while` loop:


```

            +--------------------+

            |     Condition      |

            +--------------------+

                     |

                     v

       +-------------+------------+

       |             |            |

       | true        | false      |

       |             v            |

       |     +----------------+   |

       |     |  Execute Code  |   |

       |     +----------------+   |

       |             |            |

       |             v            |

       +-------------+------------+

```


### Examples


#### Example 1: Printing Numbers from 1 to 5


Here is an example of a `while` loop in C# that prints numbers from 1 to 5:


```csharp

using System;


class Program

{

    static void Main()

    {

        int i = 1;

        while (i <= 5)

        {

            Console.WriteLine(i);

            i++;

        }

    }

}

```


**Explanation**:

- **Condition**: `i <= 5;` continues the loop as long as `i` is less than or equal to 5.

- **Loop Body**: `Console.WriteLine(i);` prints the value of `i` and `i++;` increments `i` by 1 after each iteration.


**Output**:

```

1

2

3

4

5

```


#### Example 2: Reading User Input Until "exit" is Entered


Here is an example of a `while` loop in C# that reads user input repeatedly until the user types "exit":


```csharp

using System;


class Program

{

    static void Main()

    {

        string input = "";

        while (input != "exit")

        {

            Console.Write("Enter text (type 'exit' to quit): ");

            input = Console.ReadLine();

            Console.WriteLine("You entered: " + input);

        }

    }

}

```


**Explanation**:

- **Condition**: `input != "exit";` continues the loop as long as the input is not "exit".

- **Loop Body**: `Console.ReadLine();` reads user input and `Console.WriteLine();` prints it.


**Output**:

```

Enter text (type 'exit' to quit): hello

You entered: hello

Enter text (type 'exit' to quit): world

You entered: world

Enter text (type 'exit' to quit): exit

You entered: exit

```


#### Example 3: Summing Numbers Until a Negative Number is Entered


Here is an example of a `while` loop in C# that sums numbers entered by the user until a negative number is entered:


```csharp

using System;


class Program

{

    static void Main()

    {

        int sum = 0;

        int number;

        Console.WriteLine("Enter numbers to sum (negative number to stop):");

        while (true)

        {

            number = int.Parse(Console.ReadLine());

            if (number < 0) break;

            sum += number;

        }

        Console.WriteLine("Sum: " + sum);

    }

}

```


**Explanation**:

- **Condition**: The loop continues indefinitely (`while (true)`) until a negative number is entered.

- **Loop Body**: `int.Parse(Console.ReadLine());` reads and parses user input, and `sum += number;` adds the number to `sum`.

- **Break**: The loop breaks if a negative number is entered.


**Output**:

```

Enter numbers to sum (negative number to stop):

10

20

-1

Sum: 30

```


### Summary


A `while` loop in C# is a versatile construct that executes a block of code repeatedly based on a given condition. It is used when the number of iterations is not known beforehand, and the loop continues as long as the condition remains true. This makes the `while` loop suitable for scenarios where you need to keep processing data or user input until a specific condition is met.

for loop in C#

 ## C# `for` Loop: Explanation, Theory, and Examples


### Explanation


A `for` loop in C# is a control flow statement that allows code to be executed repeatedly based on a boolean condition. It is typically used when the number of iterations is known before entering the loop.


### Theory


The `for` loop in C# consists of three main parts:

1. **Initialization**: This step is executed once before the loop starts. It typically initializes one or more loop control variables.

2. **Condition**: This boolean expression is evaluated before each iteration of the loop. If the condition is true, the loop body is executed; if false, the loop terminates.

3. **Iteration**: This step is executed after each iteration of the loop body. It typically updates the loop control variables.


The basic syntax of a `for` loop in C# is:


```csharp

for (initialization; condition; iteration)

{

    // Code to be executed

}

```


### Diagram


Here is a flowchart representing the C# `for` loop:


```

            +--------------------+

            |   Initialization   |

            +--------------------+

                     |

                     v

            +--------------------+

            |     Condition      |

            +--------------------+

                     |

       +-------------+------------+

       |             |            |

       | true        | false      |

       |             v            |

       |     +----------------+   |

       |     |  Execute Code  |   |

       |     +----------------+   |

       |             |            |

       |             v            |

       |     +----------------+   |

       +----->  Iteration     +---+

             +----------------+

```


### Examples


#### Example 1: Printing Numbers from 1 to 5


Here is an example of a `for` loop in C# that prints numbers from 1 to 5:


```csharp

using System;


class Program

{

    static void Main()

    {

        for (int i = 1; i <= 5; i++)

        {

            Console.WriteLine(i);

        }

    }

}

```


**Explanation**:

- **Initialization**: `int i = 1;` initializes the loop control variable `i` to 1.

- **Condition**: `i <= 5;` continues the loop as long as `i` is less than or equal to 5.

- **Iteration**: `i++` increments `i` by 1 after each iteration.


**Output**:

```

1

2

3

4

5

```


#### Example 2: Iterating Over an Array


Here is an example of a `for` loop in C# that iterates over an array of fruits and prints each one:


```csharp

using System;


class Program

{

    static void Main()

    {

        string[] fruits = { "apple", "banana", "cherry" };

        for (int i = 0; i < fruits.Length; i++)

        {

            Console.WriteLine(fruits[i]);

        }

    }

}

```


**Explanation**:

- **Initialization**: `int i = 0;` initializes the loop control variable `i` to 0.

- **Condition**: `i < fruits.Length;` continues the loop as long as `i` is less than the length of the `fruits` array.

- **Iteration**: `i++` increments `i` by 1 after each iteration.


**Output**:

```

apple

banana

cherry

```


#### Example 3: Calculating the Sum of Array Elements


Here is an example of a `for` loop in C# that calculates the sum of numbers in an array:


```csharp

using System;


class Program

{

    static void Main()

    {

        int[] numbers = { 1, 2, 3, 4, 5 };

        int sum = 0;

        for (int i = 0; i < numbers.Length; i++)

        {

            sum += numbers[i];

        }

        Console.WriteLine("Sum: " + sum);

    }

}

```


**Explanation**:

- **Initialization**: `int i = 0;` initializes the loop control variable `i` to 0.

- **Condition**: `i < numbers.Length;` continues the loop as long as `i` is less than the length of the `numbers` array.

- **Iteration**: `i++` increments `i` by 1 after each iteration.

- **Sum Calculation**: `sum += numbers[i];` adds the current array element to `sum`.


**Output**:

```

Sum: 15

```


### Summary


A `for` loop in C# is a powerful construct for iterating over sequences and executing code repeatedly based on a specified condition. It consists of initialization, condition, and iteration parts, making it versatile for a wide range of applications from simple counting to complex data processing.

ref , out , Named Parameters, Optional Parameters , Params

·       By default, method can return single value or nothing.

·       By default, arguments are passed to a method by value.

·       Out and Ref helps to pass by reference

·       Ref is two way from caller to callee and back

·       out is one way it sends data back from callee to caller and any data from caller is discarded.





out is one way it sends data back from callee to caller and any data from caller is discarded.

So, the first point that you need to remember is when you want multiple outputs from a Method, then you need to use the ref and out parameters in C#.

If you look out and ref, both are closely doing the same thing. Then what are the differences between them? See below table.


Ref

Out

Used to pass a variable by reference, allowing both reading and modifying the value inside the method.

Used to pass a variable by reference, ensuring it is assigned a value within the method.

The variable must be initialized before it is passed to the method.

The variable does not need to be initialized before being passed to the method.

The method can modify the value, but it is not Mandatory.

It is Mandatory The method is required to assign a value to the out parameter before it returns.

Two-way: The method can read and modify the value.

One-way (outgoing): The method must assign a value, effectively using the parameter to return data.

Useful when the method needs to read and update the passed variable , also  multiple variables can pass.

Useful when the method needs to return multiple values or ensure that a value is assigned within the method.

Requires the ref keyword in both the method signature and the calling code.

Requires the out keyword in both the method signature and the calling code.

The memory address of the variable is passed, allowing direct modification of the original value in original memory location exempted for reference data type variables.

The memory address is also passed, but the focus is on assigning a new value rather than modifying the existing one.

 original memory location modifies, exempted for reference data type variables.



Optional parameters in C# offer a way to make method calls more flexible and concise by allowing certain parameters to have default values. This reduces the need for method overloads and makes your code easier to maintain and use, especially when a method has multiple optional settings or configurations.

Note : Optional parameters are not mandatory to pass values when calling method, it is optional and up to you.

 

Key Features of Optional Parameters:

Default Values: When defining an optional parameter, you provide a default value in the method signature. If the caller omits the argument, the default value is used.

Simplified Method Calls: Optional parameters reduce the need for method overloading, allowing a single method to cover multiple use cases with fewer parameters.

Order of Parameters: Optional parameters must come after all required (non-optional) parameters in the method signature.





Named parameters in C# enhance the flexibility and readability of method calls by allowing you to specify arguments by name and in any order. They are particularly useful in methods with many parameters, especially when some are optional.

Optional Parameters: Named parameters are often used in conjunction with optional parameters, allowing you to skip some arguments or pass them in a different order.

void PrintDetails(string name, int age, string city)

           { Console.WriteLine($"Name: {name}, Age: {age}, City: {city}"); }

// Using named parameters

PrintDetails(name: "Alice", age: 30, city: "New York");

 

void SendEmail(string to, string subject, string body, bool isHtml = false, string cc = "", string bcc = "")

{

    // Email sending logic here

}

 

// Named parameters improve readability

SendEmail(

    to: "recipient@example.com",

    subject: "Meeting Reminder",

    body: "Don't forget about the meeting tomorrow.",

    isHtml: true,

    bcc: "boss@example.com"

);

 

Key Rules for Named Parameters:

  • Order Flexibility: You can change the order of arguments when using named parameters.
  • Positional vs Named: Positional arguments must appear before any named arguments in a method call.
  • Optional Parameters: Named parameters are useful for skipping optional parameters or passing them out of order.

 

 

Benefits of Named Parameters:

  • Clarity: Makes it clear which argument corresponds to which parameter, reducing the chance of errors.
  • Maintainability: Helps in maintaining code, especially when dealing with methods that have many parameters.
  • Flexibility: Allows passing arguments in a non-standard order, which can be more intuitive in some cases.

 


What is Method in c#

 

Class is blue print for the objects

Class contains variables and methods

Variables are used to store data.

Method is block of code to perform specific task ex: AddEmployee ,  deleteEmployee , SendMessage etc.

 

As Part of Method Concept, We have know about following components which involve method definition.






Main Components in Method Declaration

1.     Access Specifier          à Control Access

2.     Method Type               à Static or Instance

3.     Return Value Type     à Result value type or void (nothing to return)

4.     Method Name                          à User Specific

5.     Parameters                   à Input values to method

 

 

Types of Methods in C#

1.       Instance Methods

2.       Static Methods

3.       Extension Methods

4.       Abstract Methods

5.       Virtual Methods

 

Types of Return Values

·       Primitive Types

·       Reference Types

·       Void

·       Tuples

·       Task and Task<T>

 

Types of Parameters

·       Value Parameters

·       Reference Parameters (ref)

·       Output Parameters (out)

·       Parameter Arrays (params)

·       Optional Parameters

 

 


Method vs function in Programming language

 

The programming languages have two concepts’ functions and methods. functions are defined in structural language and methods are defined in object-oriented language.

Function & Method is a block of code that performs a task. All of these enhance code quality and reusability.

The difference between both is given below:


Method

Function

Methods are defined in object-oriented languages like C#, Java

Functions are defined in structured languages like Pascal,C and object based language like javaScript

Methods are called using instance or object.

Functions are called independently.

 

Methods do not have independent existence they are always defined with in class.

Functions have independent existence means they can be defined outside of the class.

We can control access using access specifier.

We cannot restrict access

Methods are tied to objects and operate within a class.

 

Functions are independent, reusable code blocks.

 

Can access and manipulate object data

Can have parameters and return values

Called using the object’s name and the method name

Called by their name

Often changes the state of an object

Typically stateless

It can be public or private.

Has no visibility control, accessible from anywhere in the code.

Can access and modify the state of an object.

Cannot access or modify the state of an object.

Enables encapsulation and abstraction in object-oriented programming.

Does not support encapsulation or abstraction.

Invoked using the object or class instance followed by the dot operator (.).

Invoked using the function name followed by parentheses ().

It accepts ref variable as input

No ref variable