Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Generics to return a literal string or from Dictionary<string, object>
    text
    copied!<p>I think I outsmarted myself this time. Feel free to edit the title also I could not think of a good one.</p> <p>I am reading from a file and then in that file will be a string because its like an xml file. But in the file will be a literal value or a "command" to get the value from the workContainer</p> <p>so</p> <pre><code>&lt;Email&gt;me@company.com&lt;/Email&gt; </code></pre> <p>or </p> <pre><code>&lt;Email&gt;[? MyEmail ?]&lt;/Email&gt; </code></pre> <p>What I wanted to do instead of writing ifs all over the place to put it in a generic function</p> <p>so logic is </p> <pre><code>If Container command grab from container else grab string and convert to desired type Its up to the user to ensure the file is ok and the type is correct </code></pre> <p>so another example is </p> <p>so</p> <pre><code>&lt;Answer&gt;3&lt;/Answer&gt; </code></pre> <p>or </p> <pre><code>&lt;Answer&gt;[? NumberOfSales ?]&lt;/Answer&gt; </code></pre> <p>This is the procedure I started to work on</p> <pre><code>public class WorkContainer:Dictionary&lt;string, object&gt; { public T GetKeyValue&lt;T&gt;(string Parameter) { if (Parameter.StartsWith("[? ")) { string key = Parameter.Replace("[? ", "").Replace(" ?]", ""); if (this.ContainsKey(key)) { return (T)this[key]; } else { // may throw error for value types return default(T); } } else { // Does not Compile if (typeof(T) is string) { return Parameter } // OR return (T)Parameter } } } </code></pre> <p>The Call would be </p> <pre><code> mail.To = container.GetKeyValue&lt;string&gt;("me@company.com"); </code></pre> <p>or</p> <pre><code> mail.To = container.GetKeyValue&lt;string&gt;("[? MyEmail ?]"); int answer = container.GetKeyValue&lt;int&gt;("3"); </code></pre> <p>or</p> <pre><code> answer = container.GetKeyValue&lt;int&gt;("[? NumberOfSales ?]"); </code></pre> <p>But it does not compile?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload