Homamo
Homamo

Reputation: 19

Access a variable named as its type c#

In the following example code:

public class Foo
{
    public struct Data
    {
        public int val;
    }

    public Data Data

    void method(Foo foo)
    {
        foo.Data.val = 10;
    }
}

The previous example causes the following error:

Error 3 Ambiguity between 'Foo.Data' and 'Foo.Data'

Any idea how to fix this error without having to rename the member variable? Since I'm accessing 'Data' through an object instance, then it sounds logical to me that the compiler picks the 'Data' member variable instead of the 'Data' type.

Upvotes: 1

Views: 88

Answers (3)

Damith
Damith

Reputation: 63105

change

public Data Data;

to

public Data data;

and then

void method(Foo foo)
{
    foo.data.val = 10;
}

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109822

You simply cannot do this other than by moving the nested struct outside (or by renaming the property, which you explicitly excluded):

public struct Data
{
    public int val;
}

public class Foo
{
    public Data Data;

    void method(Foo foo)
    {
        foo.Data.val = 10;
    }
}

If you want to keep struct Data more obviously related to Foo you could put them both in a nested namespace:

namespace FooThings
{
    public struct Data
    {
        public int val;
    }

    public class Foo
    {
        public Data Data;

        void method(Foo foo)
        {
            foo.Data.val = 10;
        }
    }
}

Note: The actual error from your OP was "The type 'Demo.Foo' already contains a definition for 'Data'" (after fixing the missing ";").

Upvotes: 0

SLaks
SLaks

Reputation: 888185

This occurs, along with a second, more-obvious, error, because they both have the same fully-qualified name – they're both members of Foo.

If you move the struct outside the class, it will work fine.

Upvotes: 1

Related Questions