Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It sounds like you want your dictionary to have values of varying type; in other words, that a single dictionary might hold a <code>Func&lt;Employee, string&gt;</code> and a <code>Func&lt;Customer, string&gt;</code>.</p> <p>If that is so, then you basically have no choice but to use a common base type for the <code>TValue</code> type argument, and cast the delegates when you retrieve them from the dictionary. The common base type could be <code>System.Delegate</code> or <code>System.Object</code>.</p> <p>(There are in fact other choices than this, but they just push the casting around to a different part of the design. For example, you could write a wrapper class that handles the casting for you. Such solutions don't generally stand up to a cost-benefit analysis, though.)</p> <blockquote> <p>My dictionary will only ever hold the same type, but in different scenarios I want it to be able to hold different types. The problem I have is casting from Func to Func throws the casting exception.</p> </blockquote> <p>In that case, it's not clear why you want to have a <code>Dictionary&lt;string, Func&lt;Object, string&gt;&gt;</code> rather than a <code>Dictionary&lt;string, Func&lt;Employee, string&gt;&gt;</code>. If any given dictionary will only hold one type of delegate, then create the dictionary accordingly:</p> <pre><code>Dictionary&lt;string, Func&lt;Employee, string&gt;&gt; dict = new Dictionary&lt;string, Func&lt;Employee, string&gt;&gt;(); </code></pre> <p>If the dictionary is a member of a generic class, or a local variable or parameter of a generic method, you can use type parameters in the dictionary's declaration:</p> <pre><code>class Processor&lt;T&gt; { void Process(T value, Dictionary&lt;string, Func&lt;T, string&gt;&gt; functions) { //... } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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