C# is statically-typed at compile time, after a variable is asserted, it cannot be declared once more or accustomed store values of another kind unless that kind is convertible to the variable’s kind. as an example, there’s no conversion from Associate in Nursing number to any arbitrary string. Therefore, once you declare i as associate integer, you can’t assign the string “Hello” thereto, as is shown within the following code.

int num;
num = “string”; // Error: “Cannot implicitly convert type ‘string’ to ‘int'”

However, you may generally need to copy a price into a variable or technique parameter of another sort. for example, you may have an number variable that you just have to be compelled to pass to a technique whose parameter is written as double. or you may have to be compelled to assign a category variable to a variable of AN interface sort. These types of operations ar known as sort conversions. In C#, you’ll be able to perform the subsequent types of conversions:

Implicit conversions:

No special syntax is needed as a result of the conversion is kind safe and no knowledge are going to be lost. Examples include conversions from smaller to larger integral types, and conversions from derived categories to base categories.

// Implicit conversion. intNum long can
            // hold any value an int can hold, and more!
            int intNum = 33434;
            long longNum = intNum;

Explicit conversions (casts):

Explicit conversions need a solid operator. Casting is needed once data might be lost within the conversion, or when the conversion won’t succeed for alternative reasons. Typical examples include numeric conversion to a type that has less precision or a smaller vary, and conversion of a base-class instance to a derived category.

class Explicit
            static void Main()
                double num = 1234.7;
                int num1;
                // Cast double to int.
                num1 = (int)num;
    // Output: 1234

Leave a Reply

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