C# Programming/Keywords/explicit

From Wikibooks, open books for an open world
Jump to: navigation, search



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;


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
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach
goto if implicit in int
interface internal is lock long
namespace new null object operator
out override params private protected
public readonly ref return sbyte
sealed short sizeof stackalloc
static string struct switch this
throw true try typeof uint
ulong unchecked unsafe ushort using
var virtual void volatile while
Special C# Identifiers
add alias get global partial
remove set value where yield