Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial nested struct does not get inherited

Tags:

c#

public class Base<T>
{
    T _data;

    public partial struct Data
    {
        public T _data;
    }
}

public class Custom : Base<int>
{
    public partial struct Data
    {
        public float _bla;
        public bool _bla2;
    }

    public void BlaBla()
    {
        Data data = new Data();

        //int data = data._data; <= NOT FOUND
        float bla = data._bla;
        bool bla2 = data._bla2;
    }
}

As mentioned above, the Data class is defined twice in the parent class and the child class.

In addition, Custom defines additional member variables as needed.

However, Data._data inside the Base is not accessible.

... Why is this happening?

like image 768
Lim Avatar asked May 14 '26 20:05

Lim


2 Answers

Partial classes is just syntax sugar in msil there are no partial classes. In this case you create 2 different classes. You don't have type Data, you have types Custom.Dataand Base<T>.Data.

    Console.WriteLine(typeof(Custom.Data));
    Console.WriteLine(typeof(Base<string>.Data));

enter image description here

like image 125
Max Avatar answered May 16 '26 08:05

Max


the Data class is defined twice in the parent class and the child class

Exactly. You have two different types whose names end in Data, but they have no relation whatsoever.

From the C# specification:

Each part of a partial type declaration must include a partial modifier. It must have the same name and be declared in the same namespace or type declaration as the other parts.

Because they're nested in different types, they're different types themselves. The partial modifier does nothing in this regard; they're partial types consisting of exactly one part.

like image 34
CodeCaster Avatar answered May 16 '26 08:05

CodeCaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!