Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • C# - Get Started
  • C# - Version History
  • C# - First Program
  • C# - Keywords
  • C# - Class and Objects
  • C# - Namespace
  • C# - Variables
  • C# - Implicitly-Typed Variables
  • C# - Data Types
  • Numbers
  • Strings
  • DateTime
  • Structure
  • Enum
  • StringBuilder
  • Anonymous Types
  • Dynamic Types
  • Nullable Types
  • C# - Value & Reference Types
  • C# - Interface
  • C# - Operators
  • C# - if else Statements
  • C# - Ternary Operator ?:
  • C# - Switch
  • C# - For Loop
  • C# - While Loop
  • C# - Do-while Loop
  • C# - Partial Class
  • C# - Static
  • C# - Array
  • Multidimensional Array
  • Jagged Array
  • C# - Indexer
  • C# - Generics
  • Generic Constraints
  • C# - Collections
  • ArrayList
  • List
  • SortedList
  • Dictionary
  • Hashtable
  • Stack
  • Queue
  • C# - Tuple
  • C# - ValueTuple
  • C# - Built-in Exceptions
  • Exception Handling
  • throw
  • Custom Exception
  • C# - Delegates
  • Func Delegate
  • Action Delegate
  • Predicate Delegate
  • Anonymous Methods
  • C# - Events
  • C# - Covariance
  • C# - Extension Method
  • C# - Stream I/O
  • C# - File
  • C# - FileInfo
  • C# - Object Initializer
  • OOP - Overview
  • Object-Oriented Programming
  • Abstraction
  • Encapsulation
  • Association & Composition
  • Inheritance
  • Polymorphism
  • Method Overriding
  • Method Hiding
  • C# - Solid Principles
  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle
  • Design Patterns
  • Singleton
  • Abstract Factory
  • Factory Method
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

C# - Dynamic Types

C# 4.0 (.NET 4.5) introduced a new type called dynamic that avoids compile-time type checking. A dynamic type escapes type checking at compile-time; instead, it resolves type at run time.

A dynamic type variables are defined using the dynamic keyword.

Example: dynamic Variable
dynamic MyDynamicVar = 1;

The compiler compiles dynamic types into object types in most cases. However, the actual type of a dynamic type variable would be resolved at run-time.

Example: dynamic Type at run-time
dynamic MyDynamicVar = 1;

Console.WriteLine(MyDynamicVar.GetType());
Output:
System.Int32

Dynamic types change types at run-time based on the assigned value. The following example shows how a dynamic variable changes type based on assigned value.

Example: dynamic
static void Main(string[] args)
{
    dynamic MyDynamicVar = 100;
    Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());

    MyDynamicVar = "Hello World!!";
    Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());

    MyDynamicVar = true;
    Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());

    MyDynamicVar = DateTime.Now;
    Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());
}
Try it
Output:
Value: 100, Type: System.Int32
Value: Hello World!!, Type: System.String
Value: True, Type: System.Boolean
Value: 01-01-2014, Type: System.DateTime

The dynamic type variables is converted to other types implicitly.

Example: dynamic Type Conversion
dynamic d1 = 100;
int i = d1;
		
d1 = "Hello";
string greet = d1;
		
d1 = DateTime.Now;
DateTime dt = d1;

Methods and Parameters

If you assign a class object to the dynamic type, then the compiler would not check for correct methods and properties name of a dynamic type that holds the custom class object. Consider the following example.

Example: Calling Methods
class Program
{
    static void Main(string[] args)
    {
        dynamic stud = new Student();

        stud.DisplayStudentInfo(1, "Bill");// run-time error, no compile-time error
        stud.DisplayStudentInfo("1");// run-time error, no compile-time error
        stud.FakeMethod();// run-time error, no compile-time error
    }
}

public class Student
{
    public void DisplayStudentInfo(int id)
    {
    }
}
Try it

In the above example, the C# compiler does not check for the number of parameters, parameters type, or non-existent. It validates these things at run-time, and if it is not valid, then throws a run-time exception. Note that Visual Studio IntelliSense is not supported for the dynamic types. Note that Visual Studio IntelliSense is not supported for the dynamic types.

The dynamic language runtime (DLR) API provides the infrastructure that supports the dynamic type in C#. For more information about the DLR, visit Dynamic Language Runtime Overview.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.