Valid GUID string gives Invalid cast from 'System.String' to 'System.Guid'

6k views Asked by At

I'm running the following code:

var guidStr = "C105534D-E001-46F1-874A-322E5E0E132C";
var guid1 = Guid.Parse(guidStr);
var guid2 = Convert.ChangeType(guidStr, typeof(Guid));
Console.WriteLine(guid1 + " " + guid2);

And while guid1 is getting a value just fine, guid2 line throws an exception:

Invalid cast from 'System.String' to 'System.Guid'.
at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
at System.String.System.IConvertible.ToType(Type type, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType)

What is the difference?

Unfortunately I'm using a given dll that fails on the second parsing, so cannot really change the implementation, only my input.

1

There are 1 answers

3
Abion47 On BEST ANSWER

Guid.Parse takes a string and interprets the string value into a Guid object. Convert.ChangeType attempts to directly change the string instance itself into a Guid.

Imagine the difference as being between reading a recipe from a cookbook to make a meal and trying to turn the cookbook itself into dinner.