Showing posts with label C# Advanced Features. Show all posts
Showing posts with label C# Advanced Features. Show all posts

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.

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.