Correct usage of dynamic in C#
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.
