09 Sep

Optional Argument in C# 4.0

This example shows how to use of Optional Argument in C# 4.0.

Each optional parameter has a default value as its part of the definition. If no argument is sent for the optional parameter, default value is being used. Also, default value of the optional parameter must be constant and optional parameter must define at the end of the all required parameter. It can be applied on constructor, method, and indexer.

Usage :

            OptionalArgument("Test", 123);
            OptionalArgument("Test", 123, optionalParam2:"New Default 2");

Sample Method :

        private void OptionalArgument(string requiredParam1, 
                                      int requiredParam2, 
                                      string optionalParam1 = "Default 1", 
                                      string optionalParam2 = "Default 2")
            //do anything
09 Sep

Dynamic Type in C# 4.0

This example shows how to use dynamic type in C#.

C# 4.0 allows a new static type called “dynamic”. Any operation on the object of type dynamic resolve at runtime. So, it gets escaped from compile type checking. But if any error, it caught at runtime. Also, the dynamic type allows us to access the object, without knowing type of the object at compile time. It causes no intelli-sense support.

Sample Usage :

            dynamic dynamicObj = "This is a dynamic type";
            Type dynObjType = dynamicObj.GetType();
            //This is a dynamic type

In above code, a variable of type dynamic is defined. This type is resolved in type string at runtime. We are printing the string value, and type.