Can't access public member from C# (works in VB, C++/CLI)

G

Guest

I got the following code

public ref class A {
value struct PrivateType sealed { Int32 id; };
public:
ref struct B abstract sealed {
static const PrivateType x = {1};
static const PrivateType y = {2};
};
A() { }
property PrivateType P { void set(PrivateType p) { mt = p; } }
private:
PrivateType mt;
};

The assmbly compiles fine with a warning about B:x & B:y using a private
type but that is what I want. (I want to ensure that only the constants
within the class are used with the property P and I don't want to use an enum)

It also works fine to use the assembly from VB
Dim x As New A()
x.P = A.B.x

and C++/CLI
A^ x = gcnew A();
x->P = A::B::x;

But not from C#
A x = new A();
x.P = A.B.x;

error: A.P is inaccessible due to its protection level.
error: A.B.x is inaccessible due to its protection level.

Also got strange warnings from FxCop
- A+B.x Non-constant fields should not be visible
Static fields should be constant

isn't that what "static const" means?

When looking at the type PrivateType in FxCop it says IsUnmanaged=True

MSIL says:
set_P: public hidebysig specialname instance void
A:B:x: public static valuetype Test.A/PrivateType
modopt([mscorlib]System.Runtime.CompilerServices.IsConst)
 
B

Ben Voigt

wpcmame said:
I got the following code

public ref class A {
value struct PrivateType sealed { Int32 id; };
public:
ref struct B abstract sealed {
static const PrivateType x = {1};
static const PrivateType y = {2};
};
A() { }
property PrivateType P { void set(PrivateType p) { mt = p; } }
private:
PrivateType mt;
};

The assmbly compiles fine with a warning about B:x & B:y using a private
type but that is what I want. (I want to ensure that only the constants
within the class are used with the property P and I don't want to use an
enum)

It also works fine to use the assembly from VB
Dim x As New A()
x.P = A.B.x

and C++/CLI
A^ x = gcnew A();
x->P = A::B::x;

But not from C#
A x = new A();
x.P = A.B.x;

error: A.P is inaccessible due to its protection level.
error: A.B.x is inaccessible due to its protection level.

Also got strange warnings from FxCop
- A+B.x Non-constant fields should not be visible
Static fields should be constant

isn't that what "static const" means?

No, C++/CLI has a keyword literal which is the same as C# const. C++/CLI
const is meaningless to the CLR, it marks it with an attribute which is only
understood by the C++/CLI compiler.
When looking at the type PrivateType in FxCop it says IsUnmanaged=True

MSIL says:
set_P: public hidebysig specialname instance void
A:B:x: public static valuetype Test.A/PrivateType
modopt([mscorlib]System.Runtime.CompilerServices.IsConst)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top