Home

Vici Core - String Converter

String to numeric conversions

Strings are converted to a numeric value according to the following rules:

FromToOn successOn failure
stringint/uintNumeric value0
stringint?/uint?Numeric valuenull
stringshortNumeric value0
stringshort?Numeric valuenull
stringlong/ulongNumeric value0
stringlong?/ulong?Numeric valuenull
stringdecimalNumeric value. Both '.' and ',' are treated as decimal separator0
stringdecimal?Numeric value. Both '.' and ',' are treated as decimal separatornull
stringfloat/doubleNumeric value. Both '.' and ',' are treated as decimal separator0
stringfloat?/double?Numeric value. Both '.' and ',' are treated as decimal separatornull

Examples:

StringConvert toResult
"1"int1
"5.4"decimal5.4
"5,4"decimal5.4
nulldecimal0
""decimal0

String to DateTime conversions

Converting strings to DateTime values is a little more complicated, but the base .NET Framework does a pretty good job, so the Vici conversion is similar to the built-in stuff (but a little easier to use).

To convert a string to a DateTime, you should tell the converter what date formats should be expected:

DateTime? dt1 = s.Convert<DateTime?>("MM/dd/yyyy HH:mm:ss","yyyy-MM-dd HH:mm:ss.FFFFF");

If you always use the same date formats, you can set this as the default:

StringConverter.RegisterDateFormats("MM/dd/yyyy HH:mm:ss","yyyy-MM-dd HH:mm:ss.FFFFF");

DateTime? dt1 = s.Convert<DateTime?>();

FromToOn successOn failure
stringDateTimeDate valueDateTime.MinValue
stringDateTime?Date valuenull

String to enum conversions

The Vici Converter can convert numeric and named values to enum values.

For example:

enum LogLevel { Debug = 0, Information = 1, Error = 2, FatalError = 3 };

"1".Convert<LogLevel>(); // returns LogLevel.Information
"3".Convert<LogLevel>(); // returns LogLevel.FatalError
"Error".Convert<LogLevel>(); // return LogLevel.Error

If a value can't be converted, the default is returned, which is the value 0 (zero) casted to the enum type (according to the C# specs). If the target type is nullable and the conversion fails, null is returned.

For example:

enum LogLevel { Debug = 0, Information = 1, Error = 2, FatalError = 3 };

"5".Convert<LogLevel>(); // returns LogLevel.Debug
"Bogus".Convert<LogLevel>(); // returns LogLevel.Debug
"5".Convert<LogLevel?>(); // returns null
"Bogus".Convert<LogLevel?>(); // returns null

If you want to have your own default value when conversion fails, you should use the nullable conversion and use the ?? operator:

enum LogLevel { Debug = 0, Information = 1, Error = 2, FatalError = 3 };

LogLevel logLevel = "5".Convert<LogLevel?>() ?? LogLevel.Information;
LogLevel logLevel = "Bogus".Convert<LogLevel?>() ?? LogLevel.Information;

String to boolean conversions

Conversion from string to boolean is done according to fixed true and false string values:

String valueboolean value
"1"true
"T" or "T"true
"Y" or "y"true
"True" or "true" or "True"true
"Yes" or "YES" or "yes"true
anything elsefalse