1
votes

When writing a client app in Winforms, I came across this question about placing a button within a text box without it interfering with the view of the textbox itself.

In that answer, I noticed the extern modifier, which I hadn't seen in code before.

From MSDN:

"The extern modifier is used to declare a method that is implemented externally. A common use of the extern modifier is with the DllImport attribute when you are using Interop services to call into unmanaged code."

Which is exactly how I'm seeing it used in the related question. I don't understand why it would be necessary to call a user32 external function for this, but that should probably be asked in a separate question.

So my question is, when would extern be the modifier I should use? Why is it better than simply adding the dll to your references and using it directly?

1
What about if that library is not a .NET dll? - L.B

1 Answers

3
votes

Don't confuse unmanaged DLLs with .NET assemblies. Just because the extension is .dll doesn't mean you can add a reference to it.

Quite simply: If you want to call a C function in an unmanaged DLL, you use [DllImport(...)] and the static extern modifiers. Adding it as a reference will not work because it is not a .NET assembly.

If you want to call a method in a managed .NET assembly, you add it as a reference and then you can invoke the method directly using C# code.