KGy SOFT

ObjectExtensionsConvertTTarget Method (Object, CultureInfo)

KGy SOFT Core Libraries Help
Converts an Object specified in the obj parameter to the desired TTarget.

Namespace:  KGySoft.CoreLibraries
Assembly:  KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 5.0.0
Syntax

public static TTarget Convert<TTarget>(
	this Object obj,
	CultureInfo culture = null
)

Parameters

obj
Type: SystemObject
The object to convert.
culture (Optional)
Type: System.GlobalizationCultureInfo
The culture to use for the conversion. If , then the InvariantCulture will be used. This parameter is optional.
Default value: .

Type Parameters

TTarget
The desired type of the return value.

Return Value

Type: TTarget
An object of TTarget, which is the result of the conversion.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type Object. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).
Exceptions

ExceptionCondition
ArgumentExceptionobj cannot be converted to TTarget.
Remarks

The method firstly tries to use registered direct conversions between source and target types, then attempts to perform the conversion via IConvertible types and registered TypeConverters. If these attempts fail, then the registered conversions tried to be used for intermediate steps, if possible.

New conversions can be registered by the RegisterConversion Type extension methods.

A TypeConverter can be registered by the RegisterTypeConverter Type extension method.

Tip Tip
The registered conversions are tried to be used for intermediate conversion steps if possible. For example, if a conversion is registered from Int64 to IntPtr, then conversions from other convertible types become automatically available using the Int64 type as an intermediate conversion step.

TTarget can be even a collection type if obj is also an IEnumerable implementation. The target collection type must have either a default constructor or a constructor that can accept a list, array or dictionary as an initializer collection.

Examples

Tip Tip
Try also online.
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using KGySoft.CoreLibraries;

public class Example
{
    public static void Main()
    {
        // between convertible types: like the Convert class but supports also enums in both ways
        ConvertTo<int>("123"); // culture can be specified, default is InvariantCulture
        ConvertTo<float>(ConsoleColor.Blue);
        ConvertTo<ConsoleColor>(13); // this would fail by Convert.ChangeType

        // TypeConverters are used if possible:
        ConvertTo<Guid>("AADC78003DAB4906826EFD8B2D5CF33D");

        // New conversions can be registered:
        ConvertTo<IntPtr>(42L); // fail
        typeof(long).RegisterConversion(typeof(IntPtr), (obj, type, culture) => new IntPtr((long)obj));
        ConvertTo<IntPtr>(42L); // success

        // Registered conversions can be used as intermediate steps:
        ConvertTo<IntPtr>('x'); // char => long => IntPtr

        // Collection conversion is also supported:
        ConvertTo<bool[]>(new List<int> { 1, 0, 0, 1 });
        ConvertTo<List<int>>("Blah"); // works because string is an IEnumerable<char>
        ConvertTo<string>(new[] { 'h', 'e', 'l', 'l', 'o' }); // because string has a char[] constructor
        ConvertTo<ReadOnlyCollection<string>>(new[] { 1.0m, 2, -1 }); // via the IList<T> constructor

        // even between non-generic collections:
        ConvertTo<ArrayList>(new HashSet<int> { 1, 2, 3 });
        ConvertTo<Dictionary<ConsoleColor, string>>(new Hashtable { { 1, "One" }, { "Black", 'x' } });
    }

    private static void ConvertTo<T>(object source)
    {
        Console.Write($"{source.GetType().GetName(TypeNameKind.ShortName)} => {typeof(T).GetName(TypeNameKind.ShortName)}: {AsString(source)} => ");
        try
        {
            T result = source.Convert<T>(); // a culture can be specified here for string conversions
            Console.WriteLine(AsString(result));
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.Replace(Environment.NewLine, " "));
        }
    }

    private static string AsString(object obj)
    {
        if (obj == null)
            return "<null>";

        // KeyValuePair has a similar ToString to this one
        if (obj is DictionaryEntry de)
            return $"[{de.Key}, {de.Value}]";

        if (!(obj is IEnumerable) || obj is string)
            return obj.ToString();

        return String.Join(", ", ((IEnumerable)obj).Cast<object>().Select(AsString));
    }
}

// This example produces the following output:
// String => Int32: 123 => 123
// ConsoleColor => Single: Blue => 9
// Int32 => ConsoleColor: 13 => Magenta
// String => Guid: AADC78003DAB4906826EFD8B2D5CF33D => aadc7800-3dab-4906-826e-fd8b2d5cf33d
// Int64 => IntPtr: 42 => The specified argument cannot be converted to type System.IntPtr. Parameter name: obj
// Int64 => IntPtr: 42 => 42
// Char => IntPtr: x => 120
// List`1 => Boolean[]: 1, 0, 0, 1 => True, False, False, True
// String => List`1: Blah => 66, 108, 97, 104
// Char[] => String: h, e, l, l, o => hello
// Decimal[] => ReadOnlyCollection`1: 1.0, 2, -1 => 1.0, 2, -1
// HashSet`1 => ArrayList: 1, 2, 3 => 1, 2, 3
// Hashtable => Dictionary`2: [1, One], [Black, x] => [DarkBlue, One], [Black, x]
See Also

Reference