When we import legacy dlls in C# we use something like the following notation:
[DllImport("user32.dll")] // Why am I enclosed in "["s
static extern int MessageBoxA(int hWnd, string strMsg, string strCaption, int iType);
OR also:
[MarshalAs(UnmanagedType.LPStr)] // <-- What in the world is it?
string arg1,
as mentioned here
However, this notation is not exclusively used for interop Services only like here, like:
[Conditional("DOT")] // <--- this guy right here!
static void MethodB()
{
Console.WriteLine(false);
}
but it is not listed as a preprocessor directive at msdn
What is this notation called? Where can I find literature or documentation for it?
These are attributes. They're not "preprocessor" parts of the language - unlike things like #if
, #pragma
(which are still not really handles by a preprocessor, but are meant to be thought of that way).
Basically, attributes allow you to express compile-time constant metadata about types, fields, methods, parameters, and return values. That metadata can then be retrieved at execution time via reflection.
One important thing to know in terms of finding documentation: the C# compiler will attempt to resolve an attribute like this:
[Foo]
as both Foo
and FooAttribute
. So your [MarshalAs]
example actually refers to MarshalAsAttribute
. Conventionally, all attributes end with an Attribute
suffix.