Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The type '...' has no constructors defined

Tags:

c#

constructor

I'm noticing the compiler error The type '...' has no constructors defined generated when I erroneously attempt to instantiate a particlar class.

It lead me to wonder how I would go about writing my own class that would precipitate this message when someone attempted to instantiate it.

So the code below, what do I need to do to MyClass?

namespace MyNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
        }
    }

    class MyClass
    {
        MyClass()
        {
        }
    }
}
like image 291
James Wiseman Avatar asked Aug 05 '11 14:08

James Wiseman


3 Answers

This error (CS0143) occurs if the class only defines an internal constructor and you try to instantiate it from another assembly.

public class MyClass
{
    internal MyClass()
    {
    }
}
like image 190
Frédéric Hamidi Avatar answered Nov 20 '22 08:11

Frédéric Hamidi


Also this error could be cause if you are compiling with Framework 4 or higher and embedding the Interop Types into your managed assembly. To get rid of this error you need to turn off (No embed) the Embedded Interop Types.

Instructions to turn off embedding:

  1. On VS2010 Solution Explorer, right click on the Interop Reference that you are using.
  2. Select Properties and look for Embed Interop Types
  3. Change it from True to False

You can read about Embedded Interop Types here.

Pablo

like image 31
Pabinator Avatar answered Nov 20 '22 08:11

Pabinator


I've managed to reproduce this by:

  • Creating a static class in a DLL
  • Using ildasm to decompile it to IL
  • Editing the IL to remove the "abstract" and "sealed" modifiers from the class
  • Rebuilding the DLL with ilasm
  • Compiling a program which tries to create an instance of the class

If you don't remove the abstract/sealed modifiers, the C# compiler recognizes it as a static class and gives a different error message. Of course, you could start off with a "normal" type and just remove the constructors, too.

EDIT: I actually thought I hadn't submitted this, as I saw the "internal" constructor one first. However, I'll leave it now as my version makes the C# compiler correct - there's a difference between a type having no accessible constructors and genuinely having no constructors :)

like image 12
Jon Skeet Avatar answered Nov 20 '22 08:11

Jon Skeet