13

What is the Purpose of C# constructor extern modifier?

I know about usage of extern METHODS to invoke Win32 functions, but what about CONSTRUCTORS?

Please give the practical example.

Note this:

class MyClass
{
    public extern MyClass();
}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
sfedorov1982
  • 611
  • 1
  • 5
  • 7
  • 1
    Please give an example of what you mean. – Lasse V. Karlsen Mar 05 '10 at 09:18
  • I thought the MSDN version of the definition and example would help? http://msdn.microsoft.com/en-us/library/e59b22c5%28VS.80%29.aspx – o.k.w Mar 05 '10 at 09:21
  • 1
    But that doesn't work on constructors, perhaps that's his question, but I'm not sure, hence I want him to elaborate. – Lasse V. Karlsen Mar 05 '10 at 09:22
  • @Lasse: in the C# spec paragraph 10.11 Instance constructors says a constructor can be extern: `When a constructor declaration includes an extern modifier, the constructor is said to be an external constructor. Because an external constructor declaration provides no actual implementation, its constructor-body consists of a semicolon. For all other constructors, the constructor-body consists of a block which specifies the statements to initialize a new instance of the class.` – yeyeyerman Mar 05 '10 at 09:30
  • Ok, then that was unknown to me. I don't see how that would work, considering you can't actually implement the constructor. I suspect this is related to generating code with IL other places, in any case, I deleted my wrong answer. – Lasse V. Karlsen Mar 05 '10 at 10:02
  • @Lasse, as per the answer I've just added, it works if you happen to have written the CLR ;) – Rob Mar 05 '10 at 10:26

2 Answers2

6

I believe one use/purpose of an extern ctor is to have the constructor implemented within the CLR itself. if you disassemble mscorlib.dll using Reflector and look at the System.String type, you'll see:

[MethodImpl(MethodImplOptions.InternalCall)]
public extern String(char[] value);

Which basically tells us that the (char[]) ctor for the string class is externally implemented, as part of the .net runtime.

Rob
  • 45,296
  • 24
  • 122
  • 150
1

The c# spec here indicates that apart from private, internal, protected and public, extern may be used and that this is standard external reference - see here. This to me says that the contstructor is linked into the class at a later time. Just like the PInvoke calls are. There's nothing, I'm guessing, stopping the c# compiler implementer allowing linking of external .net .modules containing said external constructors.

I cannot give an example, but I suspect one way woud be to implement the constructor in MC++, or in fact just a simple IL .module.

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216