Thứ Hai, 25 tháng 1, 2010

// // Leave a Comment

explicit Keyword C#

General

When values are cast implicitally, the runtime does not need any casting in code by the developer in order for the value to be converted to its new type.

Here is an example, where the developer is casting explicitly:

//Example of explicit casting.
float fNumber = 100.00f;
int iNumber = (int)fNumber;

The developer has told the runtime, "I know what I'm doing, force this conversion."

Implicit casting means that runtime doesn't need any prompting in order to do the conversion. Here is an example of this.

//Example of implicit casting.
byte bNumber = 10;
int iNumber = bNumber;


Keyword

Notice that no casting was necessary by the developer. What is special about implicit, is that the context that the type is converted to is totally lossless i.e. converting to this type loses no information, so it can be converted back without worry.

The explicit keyword is used to create type conversion operators which can only be used by specifying an explicit type cast.

This construct is useful to help software developers write more readable code. Having an explicit cast name makes it clear that a conversion is taking place.

class Something
{
public static explicit operator Something(string s)
{
// convert the string to Something
}
}

string x = "hello";

// Implicit conversion (string to Something) generates a compile time error
Something s = x;

// This statement is correct (explicit type name conversion)
Something s = (Something) x;

0 comments: