5

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.

Mugen
  • 8,301
  • 10
  • 62
  • 140
  • 2
    The `IConvertible.ToType` implementation for `String` (invoked from `Convert.ChangeType`) delegates to a generic conversion function (`DefaultToType`) that does not support `String` to `Guid`, unfortunately. You won't be able to use `Convert` for this. – Peter Huene Jan 08 '17 at 06:10

1 Answers1

15

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.

Abion47
  • 22,211
  • 4
  • 65
  • 88
  • Anything I can do over the input to make this call succeed? – Mugen Jan 08 '17 at 06:07
  • @Mugen What is your input? What parts of the program are you required to use, and which do you have control over? – Abion47 Jan 08 '17 at 06:11
  • I have a module that gets input in a csv file and uses this functionality to import it to a TSQL DB, when reading the file, each element is cast from `String` to the matching SQL type, in this case `Guid` (`uniqueidentifier`) – Mugen Jan 08 '17 at 06:42