Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why structs cannot have extern properties, but methods are OK?

Tags:

.net

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 says

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 have asked had I not had a real application for this. I understand, that purely academic interest to understand why some things are defined the way they are is not something that motivates some of us, so here is the down to earth motivation. I have a PostSharp attribute, that injects a certain logic into the attributed extern property. Specifically, the real code looks like so:

[LoggerAccessProperty]
private static extern ILog Logger { get; }

Where PostSharp processes the LoggerAccessProperty aspect and injects the actual getter method, which surfaces the private static compiler generated ILog instance. This is part of our in-house extension of the Log4PostSharp package. At the time, we have published the extended version of Log4PostSharp at the PostSharp google code site and this attribute is my recent addition, yet unpublished.

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 here, not struct.

EDIT3

I am using .NET 4.

like image 585
mark Avatar asked Nov 05 '22 10:11

mark


1 Answers

extern properties are not allowed in structs.

like image 196
Yuriy Faktorovich Avatar answered Nov 15 '22 12:11

Yuriy Faktorovich