I have an entity that has a field that can be either an integer stored as a string or a GUID. I execute different methods based on if that field is a GUID or an integer. Can I be sure that int.TryParse will always return false if the value is a GUID, can GUID.NewGuid() return a parseable integer?
CodePudding user response:
Int is subset of Guid without braces/dashes/other garbage. In C# you can first try to parse Guid, then try to parse integer. Guid is more strict concept than integer so it will not skip cases like this (which are not integer type):
00000000000000000000200
public static object ParseUid(string inputString)
{
if(Guid.TryParse(inputString, out guidOutput))
return guidOutput;
if(int.TryParse(inputString, out intOutput))
return intOutput;
throw new NotSupportedException(inputString);
}
CodePudding user response:
According to the specifications, a GUID always contains dashes to separate the integer blocks. This means that it will never be parsable as an integer unless you remove the dashes intentionally.
CodePudding user response:
Instead of prohibiting the parsing of one value to another you could also check which type GUID currently is through the .getClass()
method, which is also less prone to Exceptions.
CodePudding user response:
a) Even if GUID does not have letters in it (that it always have), it have dashes, and also its length is very long for an integer, so you can trust on it not being parsable to int:
if(int.TryParse(key, out int result)
{
//use result
}
else
{
// use the key
}
CodePudding user response:
No you can't. If the string representation of the int
contains leading zeroes it can have a format that both int.TryParse
and GuidTryParse
could succeed with. As example:
var myid = "00000000000000000000001234567890";
var resultInt = int.TryParse(myid, out int myInt);
var resultGuid = Guid.TryParse(myid, out Guid myGuid);
if we rule out leading zeroes then you can be sure. There's no valid string representation that will both parse as guid and int due to the guid requiring 32 alphanumerical characters which will cause an overflow with the integer.