C# Keywords Tutorial Part 29: explicit

C# Keywords Tutorial Part 29: explicit

In the realm of programming, C# stands as an object-oriented language that empowers developers to create their own data types, methods, and properties. An essential element of C# is its capacity to convert data types explicitly by employing the “explicit” keyword. The present blog article is devoted to investigating the concept of the “explicit” keyword and its operations, exemplified by code snippets.

What is the “explicit” keyword in C#?

The “explicit” keyword is used in C# to explicitly convert one data type to another. This is also known as a typecast. When you use the “explicit” keyword, you are telling the compiler that you want to convert one data type to another, and you are responsible for ensuring that the conversion is valid.

How to use the “explicit” keyword in C#?

To use the “explicit” keyword in C#, you need to define a conversion operator in your class. A conversion operator is a special type of method that allows you to convert one data type to another.

Here’s an example:

public class Temperature
{
    private double degreesCelsius;

    public Temperature(double degreesCelsius)
    {
        this.degreesCelsius = degreesCelsius;
    }

    public static explicit operator Fahrenheit(Temperature temperature)
    {
        double degreesFahrenheit = (temperature.degreesCelsius * 9.0 / 5.0) + 32;
        return new Fahrenheit(degreesFahrenheit);
    }
}

In this example, we have defined a Temperature class that stores a temperature value in degrees Celsius. We have also defined an explicit conversion operator that converts a Temperature object to a Fahrenheit object.

The conversion operator is defined using the “explicit” keyword, followed by the data type that we want to convert the object to (in this case, Fahrenheit). The operator takes a single parameter of the data type that we want to convert from (in this case, Temperature).

The body of the conversion operator performs the actual conversion. In this example, we convert the temperature value from degrees Celsius to degrees Fahrenheit, and then create a new Fahrenheit object with the converted value.

Let’s see how we can use this conversion operator:

Temperature temperature = new Temperature(25);
Fahrenheit fahrenheit = (Fahrenheit)temperature;
Console.WriteLine("{0} degrees Celsius is {1} degrees Fahrenheit.", temperature.DegreesCelsius, fahrenheit.DegreesFahrenheit);

In this example, we create a new Temperature object with a value of 25 degrees Celsius. We then use the explicit conversion operator to convert the Temperature object to a Fahrenheit object.

We can then access the converted value using the DegreesFahrenheit property of the Fahrenheit object.

Output:

25 degrees Celsius is 77 degrees Fahrenheit.

Share this post

Leave a Reply

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