Reputation: 190
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?
Upvotes: 3
Views: 162
Reputation: 26468
See the other answers from @CodeCaster and @Max Mokrousov as to why.
Here's a way to have the result you want by inheriting from the base Data class:
public class Base<T>
{
T _data;
public class Data // Note that it's a class now instead of a struct
{
public T _data;
}
}
public class Custom : Base<int>
{
public class DataCustom : Base<int>.Data
{
public float _bla;
public bool _bla2;
}
public void BlaBla()
{
DataCustom data = new DataCustom();
int dataBase = data._data; // now works
float bla = data._bla;
bool bla2 = data._bla2;
}
}
Upvotes: 2
Reputation: 151720
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.
Upvotes: 3
Reputation: 1090
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.Data
and Base<T>.Data
.
Console.WriteLine(typeof(Custom.Data));
Console.WriteLine(typeof(Base<string>.Data));
Upvotes: 4