Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Well, let's use the trick ...</p> <p>What do we know? </p> <ul> <li>Value-type variable <strong>gets boxed again and again</strong> when assigned into reference-type variable</li> <li>Reference-type variable will <strong>not get boxed</strong> again ...</li> </ul> <p>So we will just check whether it gets boxed again (into another object) ... so we compare references</p> <p><code>isReferenceType</code> will be <strong>false</strong> here, because we compare 2 objects on heap (one boxed in <code>surelyBoxed</code>, one boxed just in call to ReferenceEquals):</p> <pre><code>int checkedVariable = 123; //any type of variable can be used here object surelyBoxed = checkedVariable; bool isReferenceType = object.ReferenceEquals(surelyBoxed, checkedVariable); </code></pre> <p><code>isReferenceType</code> will be <strong>true</strong> here, because we compare 1 object on heap to itself:</p> <pre><code>object checkedVariable = 123; //any type of variable can be used here object surelyBoxed = checkedVariable; bool isReferenceType = object.ReferenceEquals(surelyBoxed, checkedVariable); </code></pre> <p>This works for ANY type, not just for <strong><code>int</code></strong> and <strong><code>object</code></strong></p> <p>To put it into well-usable method:</p> <pre><code> public static bool IsReferenceType&lt;T&gt;(T input) { object surelyBoxed = input; return object.ReferenceEquals(surelyBoxed, input); } </code></pre> <p>This method can be easily used like this:</p> <pre><code>int i1 = 123; object o1 = 123; //... bool i1Referential = IsReferenceType(i1); //returns false bool o1Referential = IsReferenceType(o1); //returns true </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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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