implicit, explicit and operator keywords in C#

Goud.Kv
Posted by in C# category on for Beginner level | Points: 250 | Views : 5828 red flag

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.

Introduction

So far, we have studied constructors and their types in C#. Now let's see some of the C# conversion keywords in this chapter.

Objective

The main objective of this article is to learn implicit, explicit and operator keywords with examples in C# programming.

Conversion Keywords

C# provides some keywords for type conversions to convert between instances of compatible types. By using them, we can convert one type to another type implicitly or explicitly. Conversion creates a new value from the older one.

C# conversion keywords are,
  1. implicit
  2. explicit
  3. operator
Implicit
implicit is the C# type conversion keyword used for the normal conversions which can be done automatically.
int i = 10;  // 32 bit integer
long j = i;  // 64 bit integer // Implicit Conversion
In the above lines of code, we have a variable 'i' (32-bit integer). And we have another variable 'j' (64-bit integer).
Observe the direct (normal) conversion of 'i' to 'j' which means 32-bit to 64-bit conversion.
  • Implicit conversions doesn't need any cast expressions.
  • They allows any conversions from one class to another class without any additional code (syntax).
  • Implicit keyword cannot be used without operator keyword. It also requires a public static method. This method returns conversion type. Example,
    public static implicit operator Vehicle(....)
    {
        ...........;
    }
Let's have an example of using implicit keyword for type conversion,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Vehicle
    {
        public int vehicleId;
        public static implicit operator Brand(Vehicle v)
        {
            Brand Audi = new Brand();
            Audi.brandId = v.vehicleId + 2;
            return Audi;
        }
    }

    class Brand
    {
        public int brandId;
        public static implicit operator Vehicle(Brand b)
        {
            Vehicle Car = new Vehicle();
            Car.vehicleId = b.brandId - 1;
            return Car;
        }
    }

    class Program
    {
        static void Main()
        {
            Vehicle v = new Vehicle();
            v.vehicleId = 1;
            Console.WriteLine(v.vehicleId);

            Brand b = v;                       // Vehicle to Brand conversion (implicit)
            Console.WriteLine(b.brandId);

            Vehicle v1 = b;                    // Brand to Vehicle conversion (implicit)
            Console.WriteLine(v1.vehicleId);
        }
    }
}
In the above code, we have two classes Vehicle and Brand. Observe that both of them have implicit conversion operators.

In the Main method, we are converting Brand to Vehicle and Vehicle to Brand directly without any casts (implicit). 
Source code readability is also increased because we don't have any converting casts in the implicit conversion.

Now, if you run the above code in the console, it will display the following output,


Implicit conversions are allowed only when the below conditions are satisfied,
  • First one is the compiler's guarantee on successful conversion.
  • Next, there should be no loss of any information in the process of conversion.

Explicit
explicit is the C# conversion keyword used for converting instances of compatible types must be invoked with a cast.
  • Explicit conversions requires cast expressions.
  • Explicit keyword also cannot be used without operator keyword.
  • Explicit conversion looks like,
    int i = 10;          // 32-bit integer
    short k = (short)i;  // 16-bit integer --- Explicit conversion
    In the above lines of code, we have two variables i (32-bit integer) and k (16-bit integer). We are converting i to k by using cast (short) i.e. we are converting 32-bit integer to 16-bit integer explicitly (using cast).
Now take a look on the below example of explicit conversions,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Vehicle
    {
        public string Type { get; set; }
        public static explicit operator Brand(Vehicle v)
        {
            Brand Audi = new Brand() { Model = v.Type };
            return Audi;
        }
    }

    class Brand
    {
        public string Model { get; set; }
        public static explicit operator Vehicle(Brand b)
        {
            Vehicle Car = new Vehicle() { Type = b.Model };
            return Car;
        }
    }

    class Program
    {
        static void Main()
        {
            Brand b = new Brand();
            b.Model = "Audi A8";

            Vehicle v = (Vehicle)b;      // Brand to Vehicle conversion --- Explicit using cast
            Console.WriteLine(v.Type);

            Vehicle v1 = new Vehicle();
            v1.Type = "Facelift";

            Brand b2 = (Brand)v1;        // Vehicle to Brand conversion --- Explicit using casts
            Console.WriteLine(b2.Model);
        }
    }
}
In the above code, we have two classes Vehicle and Brand. And we have explicit conversion operator methods in both of them.

In the Main method, we are performing the explicit conversions by using cast.

Because of casts, source code readability is decreased in explicit conversions.

The above example will prints the following output in your console,


Explicit conversions are allowed even one of the below conditions are satisfied,
  • No compiler's guarantee on successful conversions.
  • There should be an information loss in the process of conversion.
Operator
operator is the C# conversion keywords which is necessary to do a type conversion in a class or struct. It can also used without conversion keywords such as implicit and explicit.

We have used operator keyword with the above implicit and explicit keywords. 

We can use operator keyword with public static methods to make them clearer by the compiler.

Let's have an example which has two static methods with overloaded operator implementations,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Vehicle
    {
        public int Id;
        public static Vehicle operator +(Vehicle v1)
        {
            Vehicle Car = new Vehicle();          
            Car.Id = v1.Id;
            return Car;
        }

        public static Vehicle operator ++(Vehicle v2)
        {
            Vehicle Jeep = new Vehicle();
            Jeep.Id = v2.Id;
            v2.Id++;                             // Incrementing the vehicle
            return v2;
        }
    }

    class Program
    {
        static void Main()
        {
            Vehicle v = new Vehicle();           // Creating Vehicle
            v++;
            Console.WriteLine(v.Id);    
            v++;
            Console.WriteLine(v.Id);

            Vehicle u = new Vehicle();           // Creating another Vehicle
            u++;
            Console.WriteLine(u.Id);
            u++;
            Console.WriteLine(u.Id);
        }
    }
}
In the above code, we have Vehicle class with two overloading methods. We have used binary (+) and unary (++) operators.

In the second method, we are incrementing the Jeep.

Now in the Main method, we created the vehicle objects and calling the methods as usually.

This code will prints the following lines in your console,


Conclusion

In this article, we have discussed with conversion keywords in C# with examples. Hope you understand.

Thank you for reading.

Regards,
Krishna.

Recommendation
Read Polymorphism, method overloading and overriding in C# after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)