C # -Anonymous constructor from a dynamic object

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 it possible to implement something like

 public static implicit operator DataPair(dynamic value) { return new DataPair(value.Key, value.Value); } 

Therefore, I can create a new instance this way

 DataPair myInstance = {"key", "value"}; 
+7
constructor c # dynamic implicit-conversion
source share
1 answer

Most likely, this will be the closest:

 public static implicit operator DataPair(string[] values) { return new DataPair(values[0], values[1]); } 

And use it like:

 DataPair myInstance = new []{"gr", "value"}; 

What you get closest is because the syntax = {"gr", "value"}; reserved for arrays that you cannot subclass.

+1
source share

All Articles