0

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

1
  • You mean value.Value = "hello"; ? Commented May 28, 2011 at 18:14

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You could run into some interesting situations with ValueContainer<object> object something; ValueContainer<object> x = new ValueContainer<object>(something); ValueContainer<object> y = (object)(new ValueContainer<object>(something));
0

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 };
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.