简体   繁体   中英

Automatic conversion of wrapper in C#

I've build wrapper-class intended to prevent reference types of being null, as a pre-condition code contract.

public sealed class NotNullable<T> 
    where T : class
{
    private T t;

    public static implicit operator NotNullable<T>(T otherT)
    {
        otherT.CheckNull("Non-Nullable type");
        return new NotNullable<T> {t = otherT};
    }

    public static implicit operator T(NotNullable<T> other)
    {
        return other.t;
    }

}

This works finely, but a cast is always needed like when dealing with Nullable:

public void Foo(NonNullable<Bar> bar)
{
    Console.WriteLine((Bar)bar);
}

Would it be possible to have the parameter of type NonNullable behave as if it were of type T, without having to cast it? Like in Spec#:

public string Foo(Bar! bar)

You could avoid the casting by making the object itself accessible via a Value property, but it's debatable whether that's any better than casting it:

Console.WriteLine(bar.Value);

There are even tricks you can use to tell tools like ReSharper that this value is not null, either via XML or in-code annotations:

[NotNull]
public T Value { get { return t; } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM