Reputation: 97
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?
Upvotes: 4
Views: 106
Reputation: 19179
You can go forward and count!
int count = 0;
MainClass tempClass = clasClass;
while (tempClass.forward != null)
{
count++;
tempClass = tempClass.forward;
}
Also you can make this a bit smaller.
int count = 0;
MainClass tempClass = clasClass;
while ((tempClass = tempClass.forward) != null) count++;
Upvotes: 2
Reputation: 1503649
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.
Upvotes: 4