Friday, March 21, 2014

Implicit Keyword in C#

In today’s post we are going to learn about implicit operator in C#. Implicit keyword is used for conversation in C#. It is used to declare an implicit user-defined type conversation operator. So with the help of implicit keyword you can convert one class into another class without writing any other syntax.

You can find more information about Implicit from following MSDN link.
http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx

Usage of Implicit Keyword in C#:


Sounds interesting!! Let’s take a example of implicit operator in so that it will be much clear. Following is a code for that.

using System;

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

            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 implicit operator Employee(User user)
        {
            Employee employee=new Employee
            {
                    FirstName = user.FirstName, 
                    LastName = user.LastName
            };
            return employee;

        }
    }
}

In above code I have created two classes “User” and “Employee”. Both contains two properties FirstName and LastName. Also in user class I have defined implicit operator Employee which convert user object into employee object.

In main function I have created object of user with first name as “Jalpesh” and last name as “Vadgama” and then assign it to Employee class. So when you assign object to employee class it will call Employee operator with implicit keyword and convert that user object into employee object.

At the end I have printed first name and last name property of Employee class and following is output as expected.

implicit-operator-c#

That’s it. It’s very easy. Hope you like it. Stay tuned for more.. Happy programming.
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