Thứ Hai, ngày 25 tháng 1 năm 2010

// // Leave a Comment

implicit 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;

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

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.

public class Fraction
{
private int _nominator;
private int _denominator;

public Fraction(int nominator, int denominator)
{
_nominator = nominator;
_denominator = denominator;
}

public float Value { get { return (float)_nominator / (float)_denominator; } }

public static implicit operator float(Fraction f)
{
return f.Value;
}

public override string ToString()
{
return _nominator + " / " + _denominator;
}
}

public class Program
{
[STAThread]
public static void Main(string[] args)
{
Fraction fractionClass = new Fraction( 1,2);
float number = 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.

0 comments: