A quick way to change your code to return the value would be to only concatenate the first character from the RGB
values:
string hex = "#" + myColor.R.ToString("X2")[0] + myColor.G.ToString("X2")[0] +
myColor.B.ToString("X2")[0];
But, since only a subset of 6-digit codes can be accurately converted to 3-digit codes (only those with repeating characters), it might be helpful to write a helper method to convert the values:
public string GetThreeDigitRGB(Color color)
{
// Get the 2-character RGB color codes
var r = color.R.ToString("X2");
var g = color.G.ToString("X2");
var b = color.B.ToString("X2");
// Every color must have a repeating character for its code, otherwise we return null
return r[0] == r[1] && g[0] == g[1] && b[0] == b[1]
? $"#{r[0]}{g[0]}{b[0]}"
: null;
}
Then your original code could be modified to create a Color
object from the input and pass it to our helper method above to get the 3-digit code (also note the change where we get the color values in the order RGBA, which is how they're passed in):
public string GetCssValue(IWebElement iwe, string cssValue)
{
var value = iwe.GetCssValue(cssValue);
string[] numbers = value.Replace("rgba(", "").Replace(")", "").Split(",");
// Note the change to get the colors in the correct order
int r = int.Parse(numbers[0]);
int g = int.Parse(numbers[1]);
int b = int.Parse(numbers[2]);
int a = int.Parse(numbers[3]);
// Create a color from the values
Color myColor = Color.FromArgb(a, r, g, b);
// Call our helper method to get the three digit code from the color
return GetThreeDigitRGB(myColor);
}