Es posible implementar un implicit cast operator, pero sólo desde o hacia tipos que defina. Por ejemplo, haciendo algo como esto ..
public class NullableExtensions
{
public static implicit operator int(int? value)
{
return value ?? default(int);
}
}
.. devolverá un error de compilación porque CS0556 el reparto no incluye el tipo definido por el usuario.
Lo más cerca que podría hacer es definir su propio tipo anulable que contiene un operador de conversión implícita:
public struct ImplicitNullable<T> where T: struct
{
public bool HasValue { get { return this._value.HasValue; } }
public T Value { get { return this._value.Value; } }
public ImplicitNullable(T value) : this() { this._value = value; }
public ImplicitNullable(Nullable<T> value) : this() { this._value = value; }
public static implicit operator ImplicitNullable<T>(T value) { return new ImplicitNullable<T>(value); }
public static implicit operator ImplicitNullable<T>(Nullable<T> value) { return new ImplicitNullable<T>(value); }
public static implicit operator T(ImplicitNullable<T> value) { return value._value ?? default(T); }
public static implicit operator Nullable<T>(ImplicitNullable<T> value) { return value._value; }
private Nullable<T> _value { get; set; }
// Should define other Nullable<T> members, especially
// Equals and GetHashCode to avoid boxing
}
Tenga en cuenta que aunque es posible escribir el código, probablemente dará lugar a difíciles de rastrear errores. Yo recomendaría usar un molde explícito o lanzar una excepción cuando el valor sea null
.
Posteriormente, puede convertir desde y hacia el esperado:
static void Main()
{
int myInt = 1;
int? nullableInt = 2;
ImplicitNullable<int> implicitInt;
// Convert from int or int?
implicitInt = myInt;
implicitInt = nullableInt;
// Convert to int or int?
myInt = implicitInt;
nullableInt = implicitInt;
}
¿En qué idioma está esto? ¿O es este lenguaje-agnóstico y no me doy cuenta? –