Table of Contents

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

value object

The object to convert.

defaultValue T

The value returned when value is null, DBNull, empty or not convertible.

Returns

T

The converted value, or defaultValue.

Type Parameters

T

The 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

value object

The object to convert.

result T

The converted value when the method returns true; otherwise the default value.

Returns

bool

True if the value was converted; false if it is null, DBNull, empty or not convertible.

Type Parameters

T

The target type. Nullable value types and enums are supported.

Examples

if (row["Count"].TryConvertTo(out int count)) { /* ... */ }