Note that there are some explanatory texts on larger screens.

plurals
  1. POHow Do Generic Methods Know About Inaccessible Types? (Or "How I Lost a Dollar")
    text
    copied!<p>So, we had a little bet on our team whether something would work or not. I lost. Here is the code:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Windows; using MyNamespace; namespace PrivateGeneric { /// &lt;summary&gt; /// Interaction logic for MainWindow.xaml /// &lt;/summary&gt; public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void WhoIsRight_Click(object sender, RoutedEventArgs e) { var store = new GenericDataStore(); try { var data = new MyPrivateClass(); store.StoreTheData(data); object theData = store.GetTheData&lt;MyPrivateClass&gt;(); if (theData == null || !(theData is MyPrivateClass)) { throw new Exception(); } MessageBox.Show("Seann was right."); } catch (Exception) { MessageBox.Show("WOOOOOOOOOT!!!!! PHIL WINS!!!!!! HAHAHAHA!!!!!! PWNED!!!!!!!"); } } private class MyPrivateClass { } } } namespace MyNamespace { public class GenericDataStore { readonly List&lt;object&gt; _store = new List&lt;object&gt;(); public void StoreTheData&lt;T&gt;(T data) { _store.Add(data); } public object GetTheData&lt;T&gt;() { //How does "t is T" work if T is a private type unknown to this class? return _store.FirstOrDefault(t =&gt; (t is T)); } } } </code></pre> <p>The question of why it works is highlighted in the code. Does "is" not need to cast to T to determine whether it is in fact a T? And does it not need the type to be accessible to do so? Obviously that's not the case, so what mechanism does the highlighted line use to make its determination?</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