Convert Generic Value to Int32

It works because GenericValue has implicit conversions defined for primitive types.
Sometimes you need specific format or type and implicit conversion is not enough of a control.

In your example, var1 is a GenericValue and var2 is an Int32. What actually happens in the addition operation, is that the Int is implicitly converted to GenericValue and the result is not an Int32, which you might expect, but a GenericValue instead.

You can check it by f.e. doing a WriteLine/MessageBox for this:
(var1 + var2).GetType.ToString
It will print out UiPath.Core.GenericValue

Now if you change var2 to be Decimal (in the example by Rafal it looks like a currency exchange rate, so the precision is required) it will throw an error, because the compiler can’t decide by itself if it should change var1 to Decimal or var2 to GenericValue.

It gets trickier the further you go…
With GenericValue you can check what’s the type of the underlying value by using GetTypeCode.
Consider these 2 scenarios:
GenericValue var1 = 123; Int32 var2 = 456; (var1 + var2).GetType.ToString // UiPath.Core.GenericValue (var1 + var2).GetTypeCode.ToString // Int32

This is as expected. But if the readout is not a whole number?

GenericValue var1 = 123.5D; // equivalent of reading 123.5 with GetText activity Int32 var2 = 456; (var1 + var2).GetType.ToString // UiPath.Core.GenericValue (var1 + var2).GetTypeCode.ToString // Decimal

This can bite back in some cases where you’re expecting a Decimal or Int, but you get the other one, and when using GenericValue you also don’t have access to type-specific methods.
Consider this easy to do mistake:
GenericValue var1 = 456D; Console.WriteLine(var1.ToString("F")); // prints F Decimal var2 = 456D; Console.WriteLine(var2.ToString("F")); // prints 456.00
This can very easily result in a very unexpected runtime error.

This got lengthy, but in short:

  • GenericValue can be used with implicit conversions as most primitive types
  • Implicit conversions can save you the hassle of casting/converting making code easier to read
  • Implicit conversions can sometimes make you end up with unexpected results
  • Using explicit conversions is sometimes needed to make sure you have the exact type you need to call correct methods and/or preserve formatting

Regards,
Andrzej

3 Likes