By 22/07/2015 6 Comments

C# as Operator

  • It performs explicit type casting or conversion of reference types.
  • If the type which will be converted is compatible with the specified type, conversion or casting is performed successfully. If either types are incompatible or casting will be failure, the (as) operator returns null value instead of generate an exception.

Example:

using System;
namespace csharpBasic
{
    // Start class definition / declaration.
    class Program
    {
        // Static main method void type declaration.
        static void Main(string[] args)
        {
            /* Initialize obj1 variable of an object type,
               assign string value to it.
               This is now string type object.
             */
            object obj1 = "Tuturials Town";

            /* Initialize obj2 variable of an object type,
               assign non-string value 100 to it. 
               This is now non-string type object.
            */ 
            object obj2 = 100;

            /* Cast or convert obj1 which is a string type object into string s1,
               this is OK both are compatible types so this successfully cast. 
               NOTICE: the (as) operator is used between obj1 and string data type,
               it means convert an object type obj1 into string. 
            */
            string s1 = obj1 as string;

            // Print s1 variable.
            Console.WriteLine(s1);

            /* Cast or convert obj2 which is a non-string type object into string s2,
               this is NOT OK both are incompatible types so this return null value. 
            */
            string s2 = obj2 as string;

            // Nothing will be printed.
            Console.WriteLine(s2);

            Console.ReadKey();

        } // End of main method definition. 
    } // End of class. 
}





Next Tutorial →


← Previous Tutorial


Posted in: C# Basics, C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .