C# Programming/Keywords/explicit
General
[edit | edit source]When values are cast implicitly, 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
[edit | edit source]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 that 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;
C# Keywords | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Special C# Identifiers (Contextual Keywords) | |||||||||||||||
| |||||||||||||||
Contextual Keywords (Used in Queries) | |||||||||||||||
|