Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# dynamic type conversions

Tags:

c#

We have 2 objects A & B: A is system.string and B is some .net primitive type (string,int etc). we want to write generic code to assign the converted (parsed) value of B into A. Any suggestions? Thanks, Adi Barda

like image 436
Adi Barda Avatar asked Mar 15 '09 17:03

Adi Barda


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is C full form?

History: The name C is derived from an earlier programming language called BCPL (Basic Combined Programming Language). BCPL had another language based on it called B: the first letter in BCPL.


4 Answers

The most pragmatic and versatile way to do string conversions is with TypeConverter:

public static T Parse<T>(string value)
{
    // or ConvertFromInvariantString if you are doing serialization
    return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}

More types have type-converters than implement IConvertible etc, and you can also add converters to new types - both at compile-time;

[TypeConverter(typeof(MyCustomConverter))]
class Foo {...}

class MyCustomConverter : TypeConverter {
     // override ConvertFrom/ConvertTo 
}

and also at runtime if you need (for types you don't own):

TypeDescriptor.AddAttributes(typeof(Bar),
    new TypeConverterAttribute(typeof(MyCustomConverter)));
like image 177
Marc Gravell Avatar answered Sep 27 '22 18:09

Marc Gravell


As already mentioned, System.Convert and IConvertible would be the first bet. If for some reason you cannot use those (for instance, if the default system conversions for the built in types is not adequate for you), one approach is to create a dictionary that holds delegates to each conversion, and make a lookup in that to find the correct conversion when needed.

For instance; when you want to convert from String to type X you could have the following:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(SimpleConvert.To<double>("5.6"));
        Console.WriteLine(SimpleConvert.To<decimal>("42"));
    }
}

public static class SimpleConvert
{
    public static T To<T>(string value)
    {
        Type target = typeof (T);
        if (dicConversions.ContainsKey(target))
            return (T) dicConversions[target](value);

        throw new NotSupportedException("The specified type is not supported");
    }

    private static readonly Dictionary<Type, Func<string, object>> dicConversions = new Dictionary <Type, Func<string, object>> {
        { typeof (Decimal), v => Convert.ToDecimal(v) },
        { typeof (double), v => Convert.ToDouble( v) } };
}

Obviously, you would probably want to do something more interesting in your custom conversion routines, but it demonstrates the point.

like image 21
driis Avatar answered Sep 27 '22 17:09

driis


What's wrong with the already existing System.Convert class and the IConvertible interface?

like image 42
Tamas Czinege Avatar answered Sep 27 '22 18:09

Tamas Czinege


There is an overview of type conversions at MSDN where you can get more info about the topic. I've found it useful.

like image 34
Vladislav Kostenko Avatar answered Sep 27 '22 18:09

Vladislav Kostenko