master_ruko
master_ruko

Reputation: 879

Can someone explain this bit of MVVM code

I am trying out this MVVM thing and am going off a blog post by John Shews (A Minimal MVVM UWP App). I think I understand most of what's going on except for a little piece in the NotificationBase file.

Here is the part I'm having trouble understanding.

public class NotificationBase<T> : NotificationBase where T : class, new()
{
    protected T This;

    public static implicit operator T(NotificationBase<T> thing) { return thing.This; }

    public NotificationBase(T thing = null)
    {
        This = (thing == null) ? new T() : thing;
    }
}

Can anyone give me a line by line description of this code? There's a bunch of stuff going on that I can't quite get a handle on.

Upvotes: 1

Views: 120

Answers (1)

AndreasHassing
AndreasHassing

Reputation: 691

Most of these concepts are explained very well in the official documentation.

With that out of the way, I'll try to explain each line, below:

public class NotificationBase<T> : NotificationBase where T : class, new()

Declares a new class named NotificationBase<T> which has a single generic type parameter (T). It derives from the class NotificationBase (the non-generic version). It has two constraints on the type parameter; it must be a class (i.e. reference type, not an enum or other integral type), and it must have a visible empty constructor (as dictated by the new() constraint).

protected T This;

Declares a protected field named This. You can use the field in instances of this class and in derived objects.

public static implicit operator T(NotificationBase<T> thing) { return thing.This; }

Adds an implicit conversion from NotificationBase<T> to T, such that you can do the following (example):

NotificationBase<string> myWrappedString = new NotificationBase<string>("Heya");
string myString = myWrappedString;
// implicit conversion is supported due to the implicit operator declared above.
public NotificationBase(T thing = null)
{
    This = (thing == null) ? new T() : thing;
}

Declares a public constructor, such that you can create instances of NotificationBase<T>. If the input is null, the constructor will just new up a thing of type T (whatever it is, as long as it has an empty constructor). A ternary operator (predicate ? then : else) is used to make the code compact and readable when assigning to the This field.

Upvotes: 3

Related Questions