Reputation: 3841
Given the following class
:
public class DataPair{
public string Key { get; set; }
public object Value { get; set; }
public DataPair(string key, object value)
{
Key = key;
Value = value;
}
}
Is there any chance to implement something like
public static implicit operator DataPair(dynamic value)
{
return new DataPair(value.Key, value.Value);
}
So I can create a new instance this way
DataPair myInstance = {"key", "value"};
Upvotes: 12
Views: 6243
Reputation: 81
Finally, with C# 7, you may use ValueTuples like
public static implicit operator DataPair((string key, object value) value)
{
return new DataPair(value.key, value.value);
}
and use it like
DataPair dp = ("key", 234);
Upvotes: 8
Reputation: 27367
This is probably the closest you're going to get:
public static implicit operator DataPair(string[] values)
{
return new DataPair(values[0], values[1]);
}
And use it like:
DataPair myInstance = new []{"gr", "value"};
That's the closest you're going to get, as the = {"gr", "value"};
syntax is reserved for arrays, which you cannot subclass.
Upvotes: 6