search
HomeBackend DevelopmentC#.Net TutorialCorrect usage of dynamic in C#

Correct usage of dynamic in C#

Dec 13, 2016 am 09:02 AM
dynamic

dynamic is a new feature of FrameWork4.0. The emergence of dynamic gives C# the characteristics of weak language types. The compiler no longer checks the type during compilation, and the default dynamic object at compile time supports any features you want. For example, even if you know nothing about the object returned by the GetDynamicObject method, you can still call the code as follows, and the compiler will not report an error:

dynamic dynamicObject = GetDynamicObject();
Console.WriteLine(dynamicObject.Name);
Console.WriteLine(dynamicObject.SampleMethod());

Speaking of correct usage, you should first point out an incorrect usage:

People often compare the keyword var with dynamic. In fact, var and dynamic are completely different concepts and should not be compared together at all. Var is actually the "syntactic sugar" thrown to us at compile time. Once compiled, the compile time will automatically match the actual type of the var variable and replace the declaration of the variable with the actual type. This looks like when we are coding It is declared using the actual type. After dynamic is compiled, it is actually an object type, but the compiler will perform special processing on the dynamic type so that it does not perform any type checking during compilation, but places the type checking at runtime.

This can be seen from the editor window of visual studio. Variables declared with var support "intelligent sensing" because visual studion can infer the actual type of the var type, but variables declared with dynamic do not support "intelligent sensing" because the compiler knows nothing about its runtime type. Know. Using "Intelligence Sense" on dynamic variables will prompt "This operation will be resolved at runtime".

The fact that the dynamic variable is an object variable can be verified through the IL code. The IL code will not be posted here. Of course, the compiler also processes dynamic declarations to distinguish direct object variables.

dynamic is highly exaggerated in MSDN as a way to simplify interoperability. I feel that it is because of this that it is misunderstood by some developers: because many developers are not exposed to coding such as COM+ and OFFICE secondary development. So there is an urgent need for a dynamic application reason. So, in daily development, I think the most valuable thing about dynamic is:

Type conversion

Conversion between instances of Dynamic type and instances of other types is very simple, and developers can easily convert between dyanmic and Switch between non-dynamic behaviors. Any instance can be implicitly converted to an instance of dynamic type, see the following example:

dynamic d1 = 7;

dynamic d2 = "a string";

dynamic d3 = System.DateTime.Today;

dynamic d4 = System.Diagnostics.Process.GetProcesses();

Conversely, an implicit conversion can be dynamically applied to any expression of type dynamic.

Vice versa, any expression of type dynamic can also be implicitly converted to other types.

int i = d1;

string str = d2;

DateTime dt = d3;

System.Diagnostics.Process[] procs = d4;

Overloading problem with dynamic type parameters in the method

If called If a method is passed an object of dynamic type, or the object being called is of dynamic type, then the overloading judgment occurs at run time rather than compile time.

Dynamic language runtime (dynamic language runtime DLR)

Dynamic language runtime is a new set of APIs in .NET Framework 4 Beta 1. It provides support for dynamic types in c# and also implements functions such as IronPython and Dynamic programming languages ​​like IronRuby.

dynamic can simplify reflection.

In the past, we used reflection like this:

public class DynamicSample
{
public string Name { get; set; }

public int Add(int a, int b)
{
return a + b;
}
}
DynamicSample dynamicSample = new DynamicSample(); //create instance为了简化演示,我没有使用反射
var addMethod = typeof(DynamicSample).GetMethod("Add");
int re = (int)addMethod.Invoke(dynamicSample, new object[] { 1, 2 });

Now, we have a simplified way of writing:

dynamic dynamicSample2 = new DynamicSample();
int re2 = dynamicSample2.Add(1, 2);

We may not be impressed by such a simplification. After all, it seems that the code does not reduce much, but if we consider both efficiency and elegance, feature, then the advantages of dynamic will appear. The compiler optimizes dynamic, which is much faster than reflection without caching. If you must compare, you can run the above two codes (the part that calls the Add method) for 1,000,000 times to draw a conclusion.



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools