Note that there are some explanatory texts on larger screens.

plurals
  1. POC# foreach loop causes CS 0246 Type or namespace could not be found
    primarykey
    data
    text
    <p>I have a foreach loop that cycles through a list of types and creates an instance of each one. However, when I build, it gives a CS0246 error ("The type or namespace could not be found ... "). Here's a simplified version of the code:</p> <pre><code>internal static class TypeManager { internal static void LoadTypes() { // Fill the list with types // Create instances of each type foreach (Type currType in Types) { Type aType = currType; // comiles fine Object newObj = (currType)Activator.CreateInstance&lt;currType&gt;; // CS 0246 } } public static List&lt;Type&gt; Types; } </code></pre> <p>Edit: Follow-up question</p> <p>My foreach loop now looks like this:</p> <pre><code>foreach (Type currType in Types) { Types.Add((Type)Activator.CreateInstance(currType)); } </code></pre> <p>with Types List now being of type Object</p> <p>This compiles fine, but when I run it, I get the following:</p> <blockquote> <pre><code>Object reference not set to an instance of an object. </code></pre> </blockquote> <p>If I break this up into two lines that first creates an object then adds it to the List, the first line is fine (the object is created successfully), but it gives me the same error message.</p> <p>Edit: Update code sample</p> <pre><code>internal static LoadPlugins() { foreach (Type currType in pluginAssembly.GetTypes()) { if (typeof(IPlugin).IsAssignableFrom(currType)) { Assembly.LoadFrom(currFile.FullName); Object pluginInstance = Activator.CreateInstance(currType); // Compiles and runs fine Plugins.Add((IPlugin)pluginInstance); // NullReferenceException break; } } } public static List&lt;IPlugin&gt; Plugins; </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.
 

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