Note that there are some explanatory texts on larger screens.

plurals
  1. POCould the CLR support a "function pointer" value type?
    text
    copied!<p>A few days ago I asked <a href="https://stackoverflow.com/questions/7905962/why-are-delegates-reference-types">why delegates are reference types</a>, based on my misguided notion that all you need for a delegate are two references: one to an object, and one to a function. What I completely overlooked (not because I wasn't aware, simply because I forgot) is that in .NET, delegates are at least <em>partially</em> in place to support events as a built-in implementation of the <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">Observer pattern</a>, which means that every delegate supports multiple subscribers by way of an <em>invocation list</em>.</p> <p>This got me thinking, delegates really play two different roles in the .NET world. One is that of a humble function pointer, such as:</p> <pre><code>Action&lt;string&gt; writeLine = Console.WriteLine; </code></pre> <p>The <em>other</em> is that of an observable:</p> <pre><code>textBox.TextChanged += HandleTextChanged; </code></pre> <p>The existence of an invocation list seems to be exclusively for the second role, as in cases like the simple <code>writeLine</code> example above you generally don't even <em>think</em> about subscribers.</p> <p>So really, it seems to me there <em>could</em> be two different "kinds" of delegates: the "function pointer" kind, and the "observable" kind. The former, it seems to me, could be a value type.</p> <p>Now, I'm not arguing that this <em>should</em> be the case, if it's even possible. I am sure there would be a lot of downsides to making this distinction between regular and multicast delegates, such as the likely high frequency of boxing if delegates were value types, the possible need to introduce a new keyword (<code>multicast</code>?), the inevitable developer confusion, etc. What I'm really curious to know is simply if it <em>would</em> be possible, from a CLR perspective, to have a value type that could act as a function pointer.</p> <p>I guess another way of asking this would be: is <code>System.Delegate</code>, with its invocation list and all, basically a fundamental CLR type; or is it a wrapper around a simpler "function reference" type that simply isn't exposed by any CLR languages?</p> <p>I apologize for all of the informal terms I've used that may have confused some of the more educated developers out there.</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