C# Keywords Tutorial Part 43: implicit

C# Keywords Tutorial Part 43: implicit

C# presents an array of keywords that assist in accomplishing different programming tasks. Among these is the “implicit” keyword, which streamlines code by enabling implicit conversions between two types. The present blog entry delves into the “implicit” keyword in C# and presents examples to aid comprehension of its workings.

Syntax of the “implicit” keyword:

The syntax of the “implicit” keyword in C# is straightforward. Here is an example of how to use it:

public static implicit operator destination-type(source-type source)
{
    // Conversion logic
}

In this code, “source-type” represents the data type you want to convert, and “destination-type” represents the data type to which you want to convert. The “implicit” keyword indicates that this is an implicit conversion operator.

Example 1: Implicit conversion of int to double

public static implicit operator double(int i)
{
    return (double)i;
}

int myInt = 10;
double myDouble = myInt; // Implicit conversion

In this example, the “implicit” keyword allows us to convert an integer variable “myInt” to a double variable “myDouble” without any explicit casting. The “implicit” operator performs the conversion automatically, and the value of “myInt” is converted to a double value.

Example 2: Implicit conversion of Fahrenheit to Celsius

public class Fahrenheit
{
    public double Degrees { get; }

    public Fahrenheit(double degrees)
    {
        Degrees = degrees;
    }

    public static implicit operator Celsius(Fahrenheit f)
    {
        return new Celsius((f.Degrees - 32) * 5 / 9);
    }
}

public class Celsius
{
    public double Degrees { get; }

    public Celsius(double degrees)
    {
        Degrees = degrees;
    }
}

Fahrenheit f = new Fahrenheit(68);
Celsius c = f; // Implicit conversion

In this example, we define two classes “Fahrenheit” and “Celsius” that represent temperature in Fahrenheit and Celsius scales, respectively. The “implicit” operator is used to convert a Fahrenheit object to a Celsius object automatically. The conversion formula is applied inside the implicit operator, which subtracts 32 from the Fahrenheit value and multiplies the result by 5/9.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *