Reputation: 251
I have this code:
public class TaskDetails
{
private Dictionary<string, string> _arguments;
public string Arguments
{
get
{
string _tmp = "";
foreach (var _item in _arguments)
{
string _str = _item.Key + ": " + _item.Value + "<br>";
_tmp += String.Join(_str, Environment.NewLine);
}
return _tmp;
}
set { _arguments = value; }
}
}
The idea is very simple: I put value into property in the form I'm comfortable with up the code (i.e. Dictionary), but I get it from property in the form for representation down the code - the string.
But IDE says about set accessor that I cannot implicitly convert type string to Dictionary. Silly IDE, I want to put in Dictionary into Dictionary-type private property.
How, then, should I do it to publicly set property as Dictionary and publicly get this property as string?
Upvotes: 0
Views: 88
Reputation: 52280
The notion of representing a dictionary as a <br>
delimited set of plaintext strings is a little unusual and will probably need tweaks at some point in the future (e.g. if you wanted to put the text into div
elements to make them valid HTML5, or if you wanted to provide escaping to prevent XSS, or you might want to use CRLF instead of Environment.Newline
to match the HTTP protocol). So I'd suggest you encapsulate that idea in a class of its own. This will improve your maintainability.
Then you can give you custom class some implicit conversion operators, and you can write code that automatically converts to/from string or dictionary, allowing you to code it the way you were thinking (even though it's doing something slightly different under the covers).
public class HtmlDictionary //Or some other name
{
private readonly Dictionary<string, string> _arguments;
public HtmlDictionary(Dictionary<string, string> arguments)
{
_arguments = arguments;
}
public override string ToString()
{
string tmp = "";
foreach (var item in arguments)
{
string str = $"{item.Key}: {item.Value}<br>\r\n";
tmp += str;
}
return tmp;
}
public static implicit operator string(HtmlDictionary input) => input.ToString();
public static implicit operator HtmlDictionary(Dictionary<string, string> input) => new HtmlDictionary(input);
}
Now you can do this:
public class TaskDetails
{
public HtmlDictionary Arguments { get; set }
}
var o = new TaskDetails();
o.Arguments = new Dictionary<string,string>();
string s = o.Arguments;
It looks like you are setting a different type than you are getting, but under the covers the compiler is just implicitly converting for you.
P.S. The underscore generally precedes member variables only. It will confuse a lot of people if you put an underscore in front of local variable names too.
Upvotes: 2