Dynamic Variable In C#
Dynamic Variables:
·        Dynamic variables are simply can be defined under the category of dynamically Typed variables.
·        These dynamically typed variables are introduced in the version of 4.0.
·        These variables know the data type at the run time or simply we can say after the compile time. But basically, this will be identified by the value assigned for the variable
·        This type of variable can be called as inferred typed variable or can be defined as data type known at the run time.
·        These variables once a value is assigned or its optional to assign the value at the time of declaration
·        If assigned, then the type of variable can be changed like string to int or int to string etc. based on the reinitialize because type is defined at run time.
·        Dynamic variable can be defined Globally and be used inside methods or properties.
Syntax:
[Access Modifier] [dynamic] [variableName] = [optional]
Example,

        #region dynamic Variable in c#

        public class DynamicVariableDemo
        {
            // its not mandate to assign value at the declaration
            dynamic validVariable;
            StringBuilder stringBuilder = new StringBuilder();

            public DynamicVariableDemo()
            {
                stringBuilder.AppendLine("==============dynamic variable Output Starts===============");

                // assigned integer value
                validVariable = 10;
            }
            public void callingMethod()
            {
                stringBuilder.AppendLine($"Type of variable - {validVariable.GetType()}");
                stringBuilder.AppendLine($"Value for variable - { validVariable}");

                stringBuilder.AppendLine("==============Assigning string Value===============");

                //re initializing the variable with string value
                validVariable = "String Value";
                stringBuilder.AppendLine($"Type of variable - {validVariable.GetType()}");
                stringBuilder.AppendLine($"Value for variable - { validVariable}");
                stringBuilder.AppendLine("=============dynamic variable Output Ends==============");

                //prinitng values
                MessageBox.Show(stringBuilder.ToString());

            }
        }


        private void button10_Click(object sender, EventArgs e)
        {
            DynamicVariableDemo dynamicVariableDemoObject = new DynamicVariableDemo();
            dynamicVariableDemoObject.callingMethod();

        }

#endregion

Output


Comments

Popular posts from this blog