mortysporty
mortysporty

Reputation: 2889

How to keep indentation from previous line when building strings

Consider the following example. I define a struct with a ToString() method

public struct InnerStruct
{
    public double a;
    public double b;

    public override string ToString()
    {
        return $"InnerStruct:\n" +
               $"    a: {a}\n" +
               $"    b: {b}";
    }
}

Calling ToString()

 var i = new InnerStruct(){a=1, b=2};
 i.ToString()
 @"InnerStruct:
     a: 1
     b: 2
 "

So that ToString() gives a nice and readable string, where a andb is indented four spaces. However, lets say I have a new struct

public struct OuterStruct
{
    public double c;
    public InnerStruct inner;

    public override string ToString()
    {
        return $"OuterStruct:\n" +
               $"    c: {c}\n" +
               $"    inner: {inner.ToString()}";
    }
}

now writing

var u = new OuterStruct(){c=3, inner=i};
u.ToString()
@"OuterStruct:
     c: 3
     inner: InnerStruct:
     a: 1
     b: 2
"

but thats not what I want. The newline \n forces the next line to start at the beginning and count four spacese from there. I want

@"OuterStruct:
     c: 3
     inner: InnerStruct:
         a: 1
         b: 2
"

I.e. I want the indentation of the members of the inner struct to start relative to the indentation of the inner struct. Any thoughts?

Upvotes: 1

Views: 72

Answers (2)

CodeCaster
CodeCaster

Reputation: 151604

You can add an overload indicating a depth:

public override string ToString() 
{ 
    return ToString(0);
}

public string ToString(int depth)
{
    var spaces = new string(' ', 4 * depth);
    return $"InnerStruct:\n" +
           $"{spaces}    a: {a}\n" +
           $"{spaces}    b: {b}";
}

And then when printing this inner struct, pass the depth:

$"    inner: {inner.ToString(1)}";

Or pass ++depth instead of 1, whichever you want.

Upvotes: 5

tmaj
tmaj

Reputation: 35037

What about an override of ToString()?

public struct InnerStruct
{
    public double a;
    public double b;

    public override string ToString()
    {
        return ToString(String.Empty);
    }

    public string ToString(string prefix )
    {
        return $"{prefix}InnerStruct:\n" +
               $"{prefix}    a: {a}\n" +
               $"{prefix}    b: {b}";
    }
}

Upvotes: 1

Related Questions