How to change the way a class/structure is printed?

Asked

Viewed 59 times

3

I have the following structure:

struct cores
{
    int r, g, b;

    public cores(int r, int g, int b)
    {
        this.r = r;
        this.g = g;
        this.b = b;
    }
}

If I had a new structure printed, it would look like this:

Console.WriteLine(new cores(1, 0, 0));
//Saída Program.cores

But I wish the way out was:

Console.WriteLine(new cores(1, 0, 0));
//Saída R: 1 - G: 0 - B: 0

How can I do that?

I know there are already some similar questions here in the OS, but none specific to the case described, and when I went looking here, it was very difficult to find, besides the content not being in good condition for learning.

2 answers

5


Some considerations would make this structure better:

using static System.Console;

public class Program {
    public static void Main() => WriteLine(new Cores(80, 20, 160));
}

struct Cores {
    public byte R { get; }
    public byte G { get; }
    public byte B { get; }
    
    public Cores(byte r, byte g, byte b) {
        R = r;
        G = g;
        B = b;
    }
    public override string ToString() => $"{R}, {G}, {B}";
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • Don’t talk like my type. ;-;

3

To do this you can give one override in the method ToString in its structure:

struct cores
{
    int r, g, b;

    public cores(int r, int g, int b)
    {
        this.r = r;
        this.g = g;
        this.b = b;
    }

    public override string ToString() {
        return $"R: {r} - G: {g} - B: {b}";
    }
}

And write normally:

Console.WriteLine(new cores(1, 0, 0));
//Saída R: 1 - G: 0 - B: 0

See working on Ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.