Note that there are some explanatory texts on larger screens.

plurals
  1. POChecking if some function parameters data types are equal due compilation on C#
    primarykey
    data
    text
    <p>I have some example data:</p> <pre><code>public struct Task { public int INT; public string STRING; public DateTime? NULLABLEDATETIME; } </code></pre> <p>And function, which uses it:</p> <pre><code>public KeyValuePair&lt;Expression&lt;Func&lt;Task, object&gt;&gt;, object&gt; Marry(Expression&lt;Func&lt;Task, object&gt;&gt; key, object value) { return new KeyValuePair&lt;Expression&lt;Func&lt;Task, object&gt;&gt;, object&gt;(key, value); } </code></pre> <p>Here is example of function call:</p> <pre><code>Marry(t =&gt; t.INT, 1984); Marry(t =&gt; t.NULLABLEDATETIME, DateTime.Now); Marry(t =&gt; t.STRING, "SomeSting"); </code></pre> <p>This code works, no questions. Unfortunatly we can also call functions like below, because String and int are both inherited from object class:</p> <pre><code>Marry(t =&gt; t.INT, "SomeSting"); </code></pre> <p>I want to say compiler, that first and second parameters have same data type: <code>int -&gt; int</code>, <code>string -&gt; string</code>, <code>DateTime? -&gt; DateTime?</code> and check it during compilation. I tried this:</p> <pre><code>public KeyValuePair&lt;Expression&lt;Func&lt;Task, T1&gt;&gt;, T2&gt; Marry&lt;T1, T2&gt;(Expression&lt;Func&lt;Task, T1&gt;&gt; key, T2 value) where T2 : T1 { return new KeyValuePair&lt;Expression&lt;Func&lt;Task, T1&gt;&gt;, T2&gt;(key, value); } </code></pre> <p>This almost works, and if I try to put wrong data like this <code>Marry(t =&gt; t.INT, "SomeSting");</code> the compiler reports an error: <em>The type 'string' cannot be used as type parameter 'T2' in the generic type or method 'Task.Marry(System.Linq.Expressions.Expression>, T2)'. There is no implicit reference conversion from 'string' to 'int'.</em></p> <p>But this solution does not work with <code>null</code>. When I call <code>Marry(t =&gt; t.NULLABLEDATETIME, null);</code> the compiler says: <em>The type arguments for method 'Marry(System.Linq.Expressions.Expression>, T2)' cannot be inferred from the usage. Try specifying the type arguments explicitly.</em></p> <p>Why? I already know the data type: <code>DateTime?</code>. I don't want to explicitly call <code>Marry&lt;DateTime?&gt;(t =&gt; t.NULLABLEDATETIME, null);</code>. How can I do this - or is there another way to check some function parameter types during compilation?</p>
    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.
 

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