C# Programming/Keywords/implicit
Cover | Introduction | Basics | Classes | Advanced Topics | The .NET Framework | Index
General
[edit | edit source ]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. floatfNumber=100.00f; intiNumber=(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. bytebNumber=10; intiNumber=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.
Keyword
[edit | edit source ]The keyword implicit
is used for a type to define how to can be converted implicitly. It is used to define what types can be converted to without the need for explicit casting.
As an example, let us take a Fraction class, that will hold a nominator (the number at the top of the division), and a denominator (the number at the bottom of the division). We will add a property so that the value can be converted to a float
.
publicclassFraction { privateintnominator; privateintdenominator; publicFraction(intnominator1,intdenominator1) { nominator=nominator1; denominator=denominator1; } publicfloatValue{get{return(float)_nominator/(float)_denominator;}} publicstaticimplicitoperatorfloat(Fractionf) { returnf.Value; } publicoverridestringToString() { return_nominator+"/"+_denominator; } } publicclassProgram { [STAThread] publicstaticvoidMain(string[]args) { FractionfractionClass=newFraction(1,2); floatnumber=fractionClass; Console.WriteLine("{0} = {1}",fractionClass,number); } }
To re-iterate, the value it implicitally casts to must hold data in the form that the original class can be converted back to. If this is not possible, and the range is narrowed (like converting double
to int
), use the explicit operator.
C# Keywords |
---|
Special C# Identifiers (Contextual Keywords) |
Contextual Keywords (Used in Queries) |