- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What if we are not sure of the type of value that we want to store in a variable. How to handle this in C#?
As C# is a strongly-typed language, every variable and constant has a pre-defined type. Before using any variable, we must tell the compiler what type of value a variable will store.
If we are not sure about the type, then it is handled using dynamic programming. Dynamic programming is supported by the dynamic keyword.
The dynamic keyword is used to declare dynamic types. The dynamic types tell the compiler that the object is defined as dynamic and skip type-checking at compiler time, delay type-checking until runtime. All syntaxes are checked and errors are thrown at runtime.
Example
using System; namespace DemoDynamicKeyword{ class Program{ 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()); } } }
Output
The output of the above example is as follows.
Value: 100, Type: System.Int32 Value: Hello World!!, Type: System.String Value: True, Type: System.Boolean Value: 01-01-2014, Type: System.DateTime
Advertisements