Dominik Amrein Dominik Amrein - 1 month ago 7
C# Question

How to get all fields of a UDT returned as string

I would like to return all fields of an UDT (user defined type) as a string.

My UDT type looks like this:

public class PointF
{
public float X { get; set; }
public float Y { get; set; }

public PointF(float x, float y)
{
this.X = x;
this.Y = y;
}
}


I would like to use the type like this:

PointF point1 = new PointF(10, 20);
System.Console.WriteLine(point1);


The return of this code should look like this:

{10, 20}


Of course I need also access to
point1.X
and
point1.Y
as float values. Any hint how to solve this would be great. Thank you!

Answer

try this:

class Program
    {
        static void Main(string[] args)
        {

            PointF point1 = new PointF(10, 20);
            System.Console.WriteLine(point1);
            Console.Read();

        }


    }
    public class PointF
    {
        public float X { get; set; }
        public float Y { get; set; }

        public PointF(float x, float y)
        {
            this.X = x;
            this.Y = y;
        }
        public override string ToString()
        {
            return "{ "+ X.ToString() + ", "+ Y.ToString() + " }";

        }
    }