Saturday, March 22, 2014

Explicit Keyword in C#

Yesterday, I have written a blog post about Implicit Keyword in C#. In today’s post we are going to learn about Explicit keyword in C#. Like Implicit keyword explicit keyword is also used for typecasting one class into another class. It is also a type conversion operator but rather then directly invoking it will invoke by cast.

As per MSDN, The Explicit keyword declares a user defined type conversation operator that must be invoked with cast.

Usage of explicit operator in C#:

Let’s take a simple example. Following is a code for that.

using System;

namespace ExplicitOperatorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            User user=new User
            {
                    FirstName = "Jalpesh",
                    LastName = "Vadgama"
            };

            Employee employee = (Employee) user;

            Console.WriteLine(employee.FirstName);
            Console.WriteLine(employee.LastName);
            Console.ReadKey();
        }
    }

    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public static explicit operator Employee(User user)
        {
            Employee employee=new Employee
            {
                    FirstName = user.FirstName, 
                    LastName = user.LastName
            };
            return employee;

        }
    }
}

I have written almost same code as we have written for implicit operator. Same two classes “Emplyee” and “User” with first name and last name operator. The only difference is I have written explicit keyword instead of implicit. And same way I have used casting in main function of console application.

In main function I have initialized class “User” with first name and last name and then type cast that in Employee class object.  Following is out put as expected.












That’s it. It is very easy. Hope you like it. Stay tuned for more..
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews