Question

I was looking at some code and saw this static implicit operator. I already read this MSDN article on static implicit operators but I still dont understand this code. Can someone please explain what the developer's intentions were.

public abstract class Envelope
{
    public static Envelope<T> Create<T>(T body)
    {
        return new Envelope<T>(body);
    }
}

public class Envelope<T> : Envelope
{
    public Envelope(T body)
    {
        this.Body = body;
    }

    public T Body { get; private set; }

    public static implicit operator Envelope<T>(T body)
    {
        return Envelope.Create(body);
    }
}
Was it helpful?

Solution 2

It's so you can create implicit conversions from T to Envelope<T>.

Here's some examples to help you understand:

Envelope<string> envelope    = "My string"; // allowed
Envelope<int>    envelopeInt = 1;           // allowed

envelopeInt = 12;                           // allowed
envelopeInt = "string";                     // not allowed (not of type int)

Console.WriteLine(envelope.Body);           // Outputs "My string"

OTHER TIPS

It defines an implicit conversion, and it allows you to do things like

Envelope<string> e = "this will be enveloped";

Which is the same as

Envelope<string> e = new Envelope<string>("this will be enveloped");

In both cases, e.Body will be that string.

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