-1

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?

LazyLeopard
  • 194
  • 1
  • 11
  • 1
    They are called "attributes" in C#. – Alex MDC Oct 20 '14 at 06:01
  • 1
    One surprising place to find documentation is MSDN... Another - clicking F1 in Visual Studio when something you are interested in is selected (class, error,...). There are also search engines that can find answers like http://www.bing.com/search?q=c%23+marshalas or https://www.google.com/search?q=c%23+marshalas ... – Alexei Levenkov Oct 20 '14 at 06:12
  • Not downvoting as question have good answer by Jon Skeet... Also some basic searches may have revealed secret nature of `MarshalAs` as regular "attribute" in .Net/C#. – Alexei Levenkov Oct 20 '14 at 06:14
  • Sorry for cluttering our precious SO. The problem was that `MarshalAs` is documented as `MarshalAsAttribute` as explained by John. This isn't revealed in basic searches mentioned while the attributes topic has not even been mentioned in many beginner C# books. – LazyLeopard Oct 20 '14 at 06:27

1 Answers1

4

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.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194