Question

Given the code:

public class Filter<T>
{
    private bool selected = false;
    public bool Selected { get { return selected; } }

    private T value;
    public T Value { get{ return this.value; } set { this.value = value; selected = true; }
}     

public class Test
{
    public void filter()
    {
        DateTime a= new DateTime();
        Nullable<DateTime> b = new DateTime(); //Work Like a Charm
        Filter<DateTime> c = new DateTime(); //Dosent Work
    }
}

In Nullable<T> the new DateTime() can be assigned directly into the variable. In my class, it doesn't work. I want to understand what I'm missing.

I think that is something simple. But I couldn't put it on words to find the answer.

Was it helpful?

Solution

You have to implement implicit operators:

public static implicit operator Filter<T>(T value)
{
    return new Filter<T>() { Value = value };
}

An implicit operator will allow you to cast the types without explicitly writing Filter<T> filter = (Filter<T>)value; (explicit cast), but rather only Filter<T> filter = value; (implicit cast).

OTHER TIPS

You need to use an implict conversion operator:

See: Implicit cast operator and the equality operator

This allows you to write code to construct your custom type from another type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top