var and dynamic in C#

var and dynamic in C#

In the evolving landscape of C# programming, the var and dynamic keywords offer unique capabilities that can enhance code flexibility and readability. While var leverages compile-time type inference, dynamic allows for runtime type flexibility. Let's explore these keywords in more detail, including advanced usage with dynamic extensions.

The var Keyword

The var keyword is used for implicit typing, where the compiler infers the type of a variable based on the assigned value. This can simplify code and improve readability without sacrificing type safety.

var number = 10; // inferred as int
var name = "Alice"; // inferred as string
var items = new List<string> { "apple", "banana" }; // inferred as List<string>

Console.WriteLine(number); // Output: 10
Console.WriteLine(name); // Output: Alice
Console.WriteLine(string.Join(", ", items)); // Output: apple, banana        

Using var with Complex Types

var person = new { Name = "John", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // Output: Name: John, Age: 30

var people = new List<dynamic>
{
    new { Name = "Alice", Age = 25 },
    new { Name = "Bob", Age = 28 }
};

foreach (var p in people)
{
    Console.WriteLine($"{p.Name} is {p.Age} years old.");
}        

The dynamic Keyword

The dynamic keyword enables dynamic typing, allowing the type of a variable to be determined at runtime. This is particularly useful for interoperability with COM objects, dynamic languages, and certain API scenarios.

Basic Example with dynamic

dynamic value = 10;
Console.WriteLine(value); // Output: 10

value = "Hello, World!";
Console.WriteLine(value); // Output: Hello, World!

value = new List<int> { 1, 2, 3 };
foreach (var item in value)
{
    Console.WriteLine(item); // Output: 1 2 3
}        

Dynamic Extension Methods

Dynamic extension methods can be used to add functionality to dynamic objects. These methods provide a way to call methods on dynamic types at runtime.

public static class DynamicExtensions
{
    public static void Print(this dynamic obj)
    {
        Console.WriteLine($"Type: {obj.GetType()}, Value: {obj}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        dynamic value = 123;
        value.Print(); // Output: Type: System.Int32, Value: 123

        value = "Hello";
        value.Print(); // Output: Type: System.String, Value: Hello

        value = new List<int> { 1, 2, 3 };
        value.Print(); // Output: Type: System.Collections.Generic.List`1[System.Int32], Value: System.Collections.Generic.List`1[System.Int32]
    }
}        

Conclusion

var: Ideal for implicit typing with strong type safety. The type is determined at compile time, making your code cleaner and more readable.

dynamic: Provides flexibility by determining the type at runtime. It is useful for scenarios where types are not known until runtime, such as with COM objects or dynamic languages.

By understanding and appropriately leveraging var and dynamic, you can write more flexible, maintainable, and readable C# code. Whether you need compile-time type safety or runtime flexibility, these keywords offer the tools you need to enhance your development workflow.

要查看或添加评论,请登录

Azizul Arif的更多文章

社区洞察