Class ObjectConversionExtensions
- Namespace
- HeroKit.Objects
- Assembly
- HeroKit.dll
Converts objects to other types.
public static class ObjectConversionExtensions
- Inheritance
-
ObjectConversionExtensions
- Inherited Members
Remarks
ConvertTo<T>(object?, T?) is lenient and returns a default value; TryConvertTo<T>(object?, out T?) reports success. Neither throws for invalid input.
Methods
ConvertTo<T>(object?, T?)
Converts an object to the specified type, or returns a default value when it cannot.
public static T? ConvertTo<T>(this object? value, T? defaultValue = default)
Parameters
valueobjectThe object to convert.
defaultValueTThe value returned when
valueis null, DBNull, empty or not convertible.
Returns
- T
The converted value, or
defaultValue.
Type Parameters
TThe target type. Nullable value types and enums are supported.
Examples
((object)"42").ConvertTo<int>(); // 42
((object)"abc").ConvertTo(-1); // -1
TryConvertTo<T>(object?, out T?)
Tries to convert an object to the specified type.
public static bool TryConvertTo<T>(this object? value, out T? result)
Parameters
valueobjectThe object to convert.
resultTThe converted value when the method returns true; otherwise the default value.
Returns
Type Parameters
TThe target type. Nullable value types and enums are supported.
Examples
if (row["Count"].TryConvertTo(out int count)) { /* ... */ }