Reputation: 1578
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
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
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