Why can't structures have external properties, but are methods okay?

Observe the following code:

[AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } public struct A { [X] public static extern int XX { get; } } 

This does not compile. The error message indicates

The modifier 'extern' is not valid for this item.

But the following code compiles OK:

 [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } public struct A { [X] public static extern int GetXX(); } 

Why???

EDIT

Guys guys. I would not ask if I had a real application for this. I understand that a purely academic interest in understanding why certain things are defined as they are is not something that motivates some of us, so there is motivation for the earth. I have a PostSharp attribute that injects certain logic into the extern attribute property. In particular, the real code looks like this:
 [LoggerAccessProperty] private static extern ILog Logger { get; } 

Where PostSharp handles the LoggerAccessProperty aspect and implements the actual getter method, which handles the private static compiler generated by the ILog instance. This is part of our internal Log4PostSharp extension. At that time, we published an extended version of Log4PostSharp on the Google PostSharp website, and this attribute is my recent addition, but not published.

EDIT2

Note that the following code compiles just fine:

 [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } public class A { [X] public static extern int XX { get; } } 

The difference is that A is a class, not a struct.

EDIT3

I am using .NET 4.

+6
source share
4 answers

extern properties are not allowed in structs.

+1
source share

The extern modifier is used to declare a method that is implemented externally.

The above is the first line of documentation for the extern keyword. (With an accent). Given that this applies only to methods (and not to properties), you need to ask: what are you even trying to do? The fact that this is a structure, not a class, and the presence of an attribute in your code examples seems red herring.

+1
source share

Since declaring an external method does not provide an actual implementation, there is no body of the method ; the method declaration simply ends with a semicolon and there are no brackets ({}) following the signature.

So, if you changed your code to:

 [LoggerAccessProperty] private static extern ILog Logger(); 

It should work well in your structure.

Link Link

0
source share

It looks like a compiler error (this will not be fixed). The property accessory compiles to methods in JSIL, so you can get around using the get_XXX method.

0
source share

All Articles