Microsoft Visual Studio 2017 Promo Code
Microsoft Office 2016 Promo Code

The as Operator Usage in C#

In C#, as operator is used to converting one type of object into specified type. That means to convert any unknow type to specified we can use as operator in C#. Let’s discuss as operator with a simple example. Open MicrosoftVisual Studio and create a Console Application, name it as CSharpAsOperator. Add a new C# class and name it as Employee.cs with some properties as shown below.

public class Employee : Company


        public int EmplId { get; set; }

        public string EmplName { get; set; }


public class Company


        public string CompanyName { get; set; }       


As shown above, Employee class inherited the Company class. Now let’s see how to use as an operator to convert one type of object to a different kind.

class Program


        static void Main(string[] args)


            Employee objEmployee = new Employee();

            objEmployee.CompanyName = "Microsoft"; 

            Company objCompany = objEmployee as Company;





As shown above we created the object of Employee class and provided value for CompanyName property. Finally, we converted the Employee class object into Company type by using as an operator. Here we did not get any error because Employee class inherited the Company class that means Company class is the parent class for Employee.


Add comment


© Copyright 2018 | Sitemap