How to create a dictionary with key type point (x, y) and value type string in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y) {
        X = x;
        Y = y;
    }

    // Override Equals
    public override bool Equals(object obj) {
        if (obj is Point other) {
            return X == other.X && Y == other.Y;
        }
        return false;
    }

    // Override GetHashCode
    public override int GetHashCode() {
        return HashCode.Combine(X, Y);
    }

    // Override ToString
    public override string ToString() {
        return $"({X}, {Y})";
    }
}

class Program
{
    static void Main()
    {
        var dict = new Dictionary<Point, string>();

        dict[new Point(2, 7)] = "A";
        dict[new Point(3, 6)] = "B";
        dict[new Point(0, 0)] = "C";

        // Print x and y separately
        foreach (var entry in dict) {
            Point key = entry.Key;
            string value = entry.Value;
            Console.WriteLine($"x: {key.X}, y: {key.Y} => {value}");
        }
    }
}



/*
run:
  
x: 2, y: 7 => A
x: 3, y: 6 => B
x: 0, y: 0 => C

*/

 



answered Aug 10 by avibootz
...