Can and Cannot of Converting Types in ASP.NET 2.0
Implicit conversion is prohibited in C# so that you don’t loose precision of a number for example. However, implicit conversion is allowed if no such loose can occur for example converting from int to double will not be a problem. Such mechanism is called “widening conversion” opposite to it is “narrowing conversion” which requires to perform explicit conversion.
{
public int Value;
Several methods of conversion are available:
- System.Conver - used between types those implement System.IConvertible Interface. If conversion is not possible with IConvertable system throws an exception InvalidCastException.
- (type) – used between types that define conversion operators.
- type.ToString, type.Parse – used between string and base types. Note ToString also returns be default name of the type.
- type.TryParse, type.TryParseExact – from string to base type and returns false if not possible.
{
public int Value;
// Implicit conversion from an integer.
public static implicit operator TypeA(int arg)
{
TypeA res = new TypeA();
res.Value = arg;
return res;
}
// Explicit conversion to an integer
public static explicit operator int(TypeA arg)
{
return arg.Value;
}
}