find and solve || findandsolve.com
Please wait.....

Static vs Dynamic Keywords In C#

 C# - Dynamic and Static Type 

   All types of OOP programming languages can normally be considered to be either dynamically typed or statically.A static keyword used for classes which is alidates the syntax or checks for any errors during the compilation of the code.And Dynamically keyword or languages validate the syntax or checks for errors only at run time.For Example JavaScript is a dynamically language and C# and Java are a static language.
C# was considered to be a statically typed language, all the code arevwritten valid at the compile time itself.The  dynamic keyword was introduction  in C# 4.0,it became a dynamic typed language also.There are two types of concept dynamic and static types in c# which are given belwo.

⦁    var was introduced in C# 3.0
⦁    dynamic was introduced in C# 4.0 

Type inference of variables 

⦁    var is a statically  variable which is it results in a strongly typed variable, The data type of these variables are inferred at compile time. This is  a based on the type of value that these variables are initialized with.
⦁    dynamic are dynamically  variables type. That  means, their type is inferred at run-time and not the compile time in contrast to var type. 

Initialization of variables 

⦁    var type of variables are required to be initialized at the time of declaration or else they encounter the compile time error: Implicitly-typed local variables must be initialized.
⦁    The dynamic type variables need not be initialized when declared.

Example: dynamic type variable
dynamic dynamicVeriableExample = 1;
In most cases,the compiler compiles dynamic types into object types.The given above statement would be compiled as:

dynamic type at compile time:

object dynamicVeriableExample = 1;

The dynamic would resolve at a runtime. You can check the type of the dynamic variable, as given belwo below: 

For Example: Get the actual type of dynamic type at runtime

     static void Main(string[] args)
        {
            dynamic dynamicVariableExample = 1;
            Console.WriteLine(dynamicVariableExample.GetType().ToString());         }


OUTPUT:
System.Int32

In the run time,a dynamic type changes its type based on the value of the expression to the right of the "=" operator. In the given below example how to dynamic variable changes its type based on its value: 

static void Main(string[] args)
        {
            dynamic dynamicVariableExample = 200;
            Console.WriteLine("Dynamic variable value: {0}, Type: {1}", dynamicVariableExample, dynamicVariableExample.GetType().ToString());
            dynamicVariableExample = "Hello World!!";             Console.WriteLine("Dynamic variable value: {0}, Type: {1}", dynamicVariableExample, dynamicVariableExample.GetType().ToString());
            dynamicVariableExample = true;             Console.WriteLine("Dynamic variable value: {0}, Type: {1}", dynamicVariableExample, dynamicVariableExample.GetType().ToString());
            dynamicVariableExample = DateTime.Now;             Console.WriteLine("Dynamic variable value: {0}, Type: {1}", dynamicVariableExample, dynamicVariableExample.GetType().ToString());         }

  Output:

Dynamic variable value: 200, Type: System.Int32
Dynamic variable value: Hello World!!, Type: System.String
Dynamic variable value: True, Type: System.Boolean
Dynamic variable value: 01-01-2019, Type: System.DateTime
 

Methods and Properties of Dynamic Type 

       If We assign a class object to the dynamic type then the compiler would not check it for correct methods and properties name of a dynamic type that holds the custom class object.Consider the given below  example. 

Example: dynamic 

public class Staff
        {
            public int StaffId { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
            public void DisplayStaffDetail()             {                 Console.WriteLine("Name: {0}", this.Name);                 Console.WriteLine("Age: {0}", this.Age);                              }         }
        class Program         {             static void Main(string[] args)             {                 dynamic dynamicStaff = new Staff();
                dynamicStaff.FakeMethod();             }         }

 In the given above example, the Staff object assigned t to a dynamic variable.you can see the  second statement in Main() method, we call FakeMethod() method, which is not exists in the Staff class.But the compiler will not give any types of  error for FakeMethod() because it skips type checking for dynamic type, instead you will get a runtime exception. 

Accepted Dynamic Type as a Method Parameter 

class Program
        {
            static void CheckValue(dynamic val)
            {
                Console.WriteLine(val);
            }
            static void Main(string[] args)             {
                CheckValue("Hello findandsolve.com example.");                 CheckValue(100);                 CheckValue(100.50);                 CheckValue(true);                 CheckValue(DateTime.Now);             }         }

OUTPUT:

Hello findandsolve.com example.
100
100.50
True
01-01-2019 10:10:50

Points to Remember : 

⦁    Resolved at runtime instead of compile time.
⦁    Compiler skips the type checking for dynamic type. So it doesn't give any types of error about dynamic types at compile time.
⦁    Do not have intellisense support in visual studio.
⦁    it's  method can have parameters of the dynamic type.
⦁    An exception will be thrown at runtime if a method or property is not compatible. 

C# - Static 

Another  programming language are like java,c++,f# etc.It's static keyword can be applied on static keyword variables,methods,classes,operators,events,properties and constructors in the c#.However, Mostly can  be used with indexers, destructors or types other than classes.
the static item can not be instantiated or the static modifier makes an item non-instantiable.If we use the static modifier applied to a class then class can not be instantiated using the new keyword.If an apply to a variable by the static modifier,The property or method of class then they can be accessed without creating an object of the class, just use class-name.propertyName, className.methodName. 

Example: C# Static class

public static class StaticClassExample
{
    public static int StaticVariable = 10;
    public static void StaticMethod()
    {
        Console.WriteLine("This is a static method.");
    }
    public static int StaticProperty { get; set; }
}
class Program {     static void Main(string[] args)     {         Console.WriteLine(StaticClassExample.StaticMethod);         StaticClassExample.StaticMethod();         StaticClassExample.StaticProperty = 200;         Console.WriteLine(StaticClassExample.StaticProperty);     } }

OUTPUT:
10
This is a static method.
200 

C# Static Constructor 

A static or non-static classes are can have a static constructor without any access modifiers such as public, private, protected, etc.These are run only once when the class is instantiated for the first time. 

For Example :Static Constructor in Static Class 

public static class StaticClass
{
    static StaticClass()
    {
        Console.WriteLine("Inside static constructor.");
    }
    public static int StaticVariable =10;
    public static void StaticMethod()
    {
        Console.WriteLine("This is static method.");
    }
    public static int StaticProperty { get; set; }
}
class Program {     static void Main(string[] args)     {         StaticClass.StaticVariable = 100;         StaticClass.StaticProperty = 200;         StaticClass.StaticVariable = 300;         StaticClass.StaticProperty = 400;
    } }
OUTPUT:

Inside static constructor.In the given above example, the static members was accessed multiple times.When any of its static members was accessed for the first time the static constructor got called only once.

For Example: Static constructor in a non-static class 

public class NonStaticClass
{
    static NonStaticClass()
    {
        Console.WriteLine("Inside static constructor.");
    }
    public void NonStaticMethod()     {         Console.WriteLine("Non-static method");     } }
class Program {     static void Main(string[] args)     {         NonStaticClass mnsObj1 = new NonStaticClass();         NonStaticClass mnsObj2 = new NonStaticClass();         NonStaticClass mnsObj3 = new NonStaticClass();     } }

OUTPUT:
Inside static constructor
In the given above example, we instantiate NonStaticClass three times but the static constructor got called only once when it instantiated for the first time.
 

Points to Remember for Static in C#:
 

⦁    It is can not be instantiated using the new keyword.
⦁    It is only access other static items.
⦁    It is share the resources between multiple users.
⦁    Static class can not be used with indexers, destructors or types other than classes.
⦁    A static constructor in a non-static class runs only once when the class is instantiated for the first time.
⦁    Static members are allocated in high frequency heap area of the memory.
⦁    A static constructor in a static class runs only once when any of its static members accessed for the first time.
 

 

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

Comments



Report Response