enashnash
enashnash

Reputation: 1578

Create an instance of a class from an instance of the type of its generic parameter

I want to do this:

public class ValueContainer<T> {
  public T Value { get; set; }
}

Then I want to assign a value to it like this:

private ValueContainer<string> value;
value = "hello";

I'm sure I've seen this somewhere but can't figure out how to do it.

TIA

Upvotes: 0

Views: 164

Answers (2)

ahawker
ahawker

Reputation: 3364

Creating your own implicit operator will take care of this problem.

class Program
{
    static void Main(string[] args)
    {    
        Container<string> container;
        container = "hello";
    }
}

public class Container<T>
{
    public T Value { get; set; }

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

Upvotes: 0

Matthew Abbott
Matthew Abbott

Reputation: 61589

You can use a custom implicit operator, e.g:

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

While this is a nice language feature of C#, it is not CLS compliant and won't be supported by other .NET languages like VB.NET, so if you are designing types to be reused with other languages, its worth baring that in mind.

Upvotes: 3

Related Questions