Saturday, 14 December 2019

C# Session 6: Implicit & Dynamic Variable in C#

Implicit & Dynamic Variable

Implicitly Typed Variable:
These types of variable are declared without specifying any type explicitly.
The type of variable gets auto assigned based on the type of value it is going to occupy.
It is introduced in C# version 3.0 and designed for not to replace normal variable but to handle some special cases like LINQ.
Also, it is termed as Local Variable because it can’t be used with method params, return types and at class level etc… and only used within a block.
var i=10;
Valid  / Invalid Statements:

using System;

namespace CSharp.Tutorial
{
    public class Program
    {
        // var myName = "Sunil"; -- Implicit type variable can't be declared at class level.
        static void Main(string[] args)
        {
            //var i = 1, a = 2; -- Multiple decleration not allowed with implicit variable.
            // var myValue; -- Implicit variable can't be declared without initialization.0
            // var name2 = null; -- Implicit variable can't contain "NULL" value.
            // var arr = { 10, 20, 30 }; -- Implicit type can't contain any object/collection.
            var arr2 = new int[] { 10, 20, 30 };    // Allowed as it can contain an expression that may have a collection
            var name = "SKMDotNet Tutorial";    // Local implicit variable
            // Impliciyly Type of variable in C#
            Console.WriteLine($"Welcome to {name}");
            Console.WriteLine($"Tyep of name is: {name.GetType().ToString()}");
            Console.ReadLine();
        }
    }
}


Dynamic Variable:
These types of variable are introduced in C# 4.0.
The type of variable doesn’t check in compile time and its gets assigned in run time.
Dynamic variable is created using dynamic keyword.
           dynamic i=10;
A class object can be assigned to a dynamic type also it can be used as method param as well so that it can accept any type of values.
It doesn’t give type checking in IDE like Visual Studio.
Compiler doesn’t throw an error for dynamic type as no type it has at compile time.


using System;

namespace CSharp.Tutorial
{
    public class Program
    {
        public static dynamic PrintInputs(dynamic value1, dynamic value2)
        {
            return value1.ToString() + value2.ToString();
        }
        static void Main(string[] args)
        {
            dynamic name = "SKMDotNet";
            Console.WriteLine($"{name} and its type is: {name.GetType().ToString()}");
            Console.WriteLine(PrintInputs(1, 2));
            Console.WriteLine(PrintInputs("SKMDotNet ", "Tutorial"));
            Console.ReadLine();
        }
    }

}

No comments:

Post a Comment

Angular 8 Session 21 - ngFor Directive In Angular

ngFor Directive Content will be resume soon. Stay tuned!