I'am sorry for my Engilsh. I have some class like this:
public class MainClass
{
public string message { get; set; }
public MainClass forward { get; set; }
}
And have Main funcion, where I'am inizialize class and fill data(in real project I have data in JSON format, where class can be embedded itself in an infinite number of times) of class:
static void Main(string[] args)
{
MainClass clasClass = new MainClass()
{
message = "Test1",
forward = new MainClass()
{
message = "Test1_1",
forward = new MainClass()
{
message = "Test1_1_1",
forward = new MainClass()
{
message = "Test1_1_1_1",
forward = new MainClass()
}
}
}
};
}
How do I get the number of nested class names , without knowing their number?
It sounds like you just want recursion:
public int GetNestingLevel(MainClass mc)
{
return mc.forward == null ? 0 : GetNestingLevel(mc.forward) + 1;
}
Or as part of MainClass
itself:
public int GetNestingLevel()
{
return mc.forward == null ? 0 : mc.forward.GetNestingLevel() + 1;
}
Or in C# 6, if you want to use the null conditional operator:
public int GetNestingLevel()
{
return (mc.forward?.GetNestingLevel() + 1) ?? 0;
}
That could cause problems if you have very deeply nested classes, in terms of blowing the stack - but it's probably the simplest approach otherwise. The alternative is to use iteration, as per M.kazem Akhgary's answer.
See more on this question at Stackoverflow