Closed
Description
Background and motivation
Convert.FromHexString("not-hex");
is throwing a System.FormatException
when input string is not a valid hex.
Like Convert.TryFromBase64Chars()
Convert.TryFromBase64String()
it would be nice to have Convert.TryFromHexString();
when validating user input it's not great to be force to put a whole try/catch block arround for readability
byte[] myBytes;
try
{
myBytes = Convert.FromHexString(inputString);
}
catch (FormatException ex)
{
throw new InvalidXxx(ex);
}
I think It would be much nicer to do
if (!Convert.TryFromHexString(inputString, out var myBytes))
throw new InvalidXxx(ex);
API Proposal
namespace System;
public class Convert
{
public static bool TryFromHexString(string s, Span<byte> bytes, out int bytesWritten)
}
API Usage
if (!Convert.TryFromHexString(inputString, out var myBytes))
throw new InvalidXxx(ex);
Alternative Designs
TryFromBase64String
returns a Span bytes
instead with the number bytesWritten
, so maybe it should be the same, but since the number of bytes are easy to guest with hex string (just divide string length by 2) I'm not sure it's useful
public static bool TryFromHexString(string s, Span<byte> bytes, out int bytesWritten)
Risks
I don't see any