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
What are the alternatives to NULL in C languageWhat are the alternatives to NULL in C languageMar 03, 2025 pm 05:37 PM

This article explores the challenges of NULL pointer dereferences in C. It argues that the problem isn't NULL itself, but its misuse. The article details best practices for preventing dereferences, including pre-dereference checks, pointer initiali

How to add next-level C compilerHow to add next-level C compilerMar 03, 2025 pm 05:44 PM

This article explains how to create newline characters in C using the \n escape sequence within printf and puts functions. It details the functionality and provides code examples demonstrating its use for line breaks in output.

Which C language compiler is better?Which C language compiler is better?Mar 03, 2025 pm 05:39 PM

This article guides beginners on choosing a C compiler. It argues that GCC, due to its ease of use, wide availability, and extensive resources, is best for beginners. However, it also compares GCC, Clang, MSVC, and TCC, highlighting their differenc

Is NULL still important in modern programming in C language?Is NULL still important in modern programming in C language?Mar 03, 2025 pm 05:35 PM

This article emphasizes the continued importance of NULL in modern C programming. Despite advancements, NULL remains crucial for explicit pointer management, preventing segmentation faults by marking the absence of a valid memory address. Best prac

What are the web versions of C language compilers?What are the web versions of C language compilers?Mar 03, 2025 pm 05:42 PM

This article reviews online C compilers for beginners, focusing on ease of use and debugging capabilities. OnlineGDB and Repl.it are highlighted for their user-friendly interfaces and helpful debugging tools. Other options like Programiz and Compil

C language online programming website C language compiler official website summaryC language online programming website C language compiler official website summaryMar 03, 2025 pm 05:41 PM

This article compares online C programming platforms, highlighting differences in features like debugging tools, IDE functionality, standard compliance, and memory/execution limits. It argues that the "best" platform depends on user needs,

Method of copying code by C language compilerMethod of copying code by C language compilerMar 03, 2025 pm 05:43 PM

This article discusses efficient code copying in C IDEs. It emphasizes that copying is an IDE function, not a compiler feature, and details strategies for improved efficiency, including using IDE selection tools, code folding, search/replace, templa

How to solve the problem of not popping up the output window by the C language compilerHow to solve the problem of not popping up the output window by the C language compilerMar 03, 2025 pm 05:40 PM

This article troubleshoots missing output windows in C program compilation. It examines causes like failing to run the executable, program errors, incorrect compiler settings, background processes, and rapid program termination. Solutions involve ch

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment