axeefectushka

Untitled

Oct 31st, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.71 KB | None | 0 0
  1. using System;
  2.  
  3. class Program
  4. {
  5.     static void Main()
  6.     {
  7.         Color red = new Color(255, 0, 0);
  8.         Color red1 = new Color(255, 0, 0);
  9.         Color green = new Color(0, 255, 0);
  10.         Color unknownColor = new Color(250, 2, 3);
  11.  
  12.         Console.WriteLine(red.ToString());
  13.         Console.WriteLine(unknownColor.ToString());
  14.  
  15.         Object obj = new Object();
  16.  
  17.         Console.WriteLine(red.Equals(null));
  18.         Console.WriteLine(red.Equals(obj));
  19.         Console.WriteLine(red.Equals(green));
  20.         Console.WriteLine(red.Equals(red1));
  21.  
  22.         Console.WriteLine($"Red's hashcode: {red.GetHashCode()}, Green's hashcode: {green.GetHashCode()}, unknownColor's hashcode: {unknownColor.GetHashCode()}");
  23.         Console.ReadKey();
  24.     }
  25. }
  26.  
  27. class Color
  28. {
  29.     public byte R { get; }
  30.     public byte G { get; }
  31.     public byte B { get; }
  32.  
  33.     public Color(byte r, byte g, byte b)
  34.     {
  35.         R = r;
  36.         G = g;
  37.         B = b;
  38.     }
  39.  
  40.     public override string ToString()
  41.     {
  42.         if (R == 255 && G == 0 && B == 0) return "Red";
  43.         if (R == 0 && G == 255 && B == 0) return "Green";
  44.         if (R == 0 && G == 0 && B == 255) return "Blue";
  45.         else
  46.         {
  47.             return $"R:{R}, G:{G}, B:{B}";
  48.         }
  49.     }
  50.  
  51.     public override bool Equals(object obj)
  52.     {
  53.         if (obj == null) return false;
  54.  
  55.         if (!(obj is Color color)) return false;
  56.  
  57.         return color.R == R && color.G == G && color.B == B;
  58.     }
  59.     public bool Equals(Color color)
  60.     {
  61.         if (color == null) return false;
  62.  
  63.        return (color.R == R && color.G == G && color.B == B);
  64.     }
  65.  
  66.     public override int GetHashCode() => (R << 2 + G << 2)<<1 + B << 2;
  67. }
Add Comment
Please, Sign In to add comment