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

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 have a new structure printed, it looks like this:

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

But I would like the output to be:

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

How can I do this?

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

asked by anonymous 10.09.2017 / 03:05

2 answers

4

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}";
}

See running on .NET Fiddle . And on Coding Ground . Also I put it in GitHub for future reference .

10.09.2017 / 03:29
3

To do this you can give a override in the < a href="https://msdn.microsoft.com/en-us/library/system.object.tostring(v=vs.110).aspx"> 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 at Ideone .

    
10.09.2017 / 03:05