Home > Net >  How to correct the constructor?
How to correct the constructor?

Time:02-14

using System;
using System.Text;
using System.Collections.Generic;

class RGB: IEquatable<RGB> {
  private byte R, G, B;

  public static RGB Red   = new(255, 0, 0);
  public static RGB Green = new(0, 255, 0);
  public static RGB Blue  = new(0, 0, 255);

  public RGB(byte R, byte G, byte B) {
    this.R = R;
    this.G = G;
    this.B = B;
  }

  public RGB(string color_hexcode){
    byte[] red_bytes   = Encoding.UTF8.GetBytes(color_hexcode[1..3]);
    byte[] green_bytes = Encoding.UTF8.GetBytes(color_hexcode[3..5]);
    byte[] blue_bytes  = Encoding.UTF8.GetBytes(color_hexcode[5..]);
    
    this.R = Convert.ToByte(Convert.ToHexString(red_bytes));
    this.G = Convert.ToByte(Convert.ToHexString(green_bytes));
    this.B = Convert.ToByte(Convert.ToHexString(blue_bytes));
  }

  public byte RedValue   { get => this.R; }
  public byte GreenValue { get => this.G; }
  public byte BlueValue  { get => this.B; }

  public bool ContainsRed   { get => this.R != 0  ? true : false; }
  public bool ContainsGreen { get => this.G != 0  ? true : false; }
  public bool ContainsBlue  { get => this.B != 0  ? true : false; }

  public bool Equals(RGB other) {
    return (this.R, this.G, this.B) == (other.R, other.G, other.B);
  }
}

class Program {
  public static void Main (string[] args) {
    RGB Yellow = new("#ffff00");
    Console.WriteLine(Yellow.ContainsBlue);
  }
}

My code causes to: Unhandled exception. System.OverflowException: Value was either too large or too small for an unsigned byte. at public RGB(string color_hexcode)....

I tried to convert the string to hexstring then the hexstring to byte. #ff is equal to decimal 255. So #ff is in bounds of byte data type. I don't get what's wrong with this code. C# must be convert #ff to byte seamlessly. Does anyone have any idea how to fix it?

CodePudding user response:

Assuming your color_hexcode is a string like #ffeecc it'd be like this:

  public RGB(string color_hexcode){

    this.R = byte.Parse(color_hexcode[1..3], NumberStyles.HexNumber);
    this.G = byte.Parse(color_hexcode[3..5], NumberStyles.HexNumber);
    this.B = byte.Parse(color_hexcode[5..7], NumberStyles.HexNumber);
  }

As for why your attempt blew up:

  • Encoding.UTF8.GetBytes() will take a string like "ff" and return the bytes that make up those chars. f is 99 or 0x63
  • This means it gives you a new byte[] {0x63, 0x63}
  • Convert.ToHexString on this gives you "6363"
  • Convert.ToByte on "6363" blows up because no matter which way you cut it, be it 6363 or 0x6363 it's bigger than a byte
  • Related