public class shape
{
public int x, y;
public class triangle
{
int sides = 3;
}
public rectangle rect = new rectangle();
public class rectangle
{
int sides = 4;
public class square
{
public string s;
}
}
}
shape a = new shape();
a.x = 4;
a.y = 3;
//print(a.triangle.sides) //no such thing
//print(a.rect.sides) //prints 4
shape.rectangle.square d = new shape.rectangle.square();
d.s = "abc";
It’s a somewhat arbitrary example, but it shows the use of nesting class definitions in C# to work like namespaces.
The inner classes can also inherit from the outer ones and the such as well but the namespace like behaviour is the same.
Except where I made it so in “shape” with “public rectangle rect = new rectangle();” the inner classes are not so much part of the outer ones. It’s more like they just all have similar names, for example they could be unstacked and the reworded with underscores “shape_rectangle_square d = new shape_rectangle_square();”.
I was wondering if there were any performance considerations to this, for example in thease situations.
shape.triangle t = new shape.triangle();
List<shape.triangle> triangles = new List<shape.triangle>();
triangles.Add(new shape.triangle());
foreach (shape.triangle t in triangles)
func(new shape.triangle(1, 2, 3), "ted");
vs
shape_triangle t = new shape_triangle();
List<shape_triangle> triangles = new List<shape_triangle>();
triangles.Add(new shape_triangle());
foreach (shape_triangle t in triangles)
func(new shape_triangle(1, 2, 3), "ted");
No. It could matter a few nanoseconds in compile-time maybe.
A class allows nested Types. This is sometimes used for (private) ‘helper’ classes and strongly related
enums. But it is about structure and organization, not about performance.In general, public nested classes are best avoided. Public enums are sligtly more common.