How to convert to an object of a certain type?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?ISO-8859-1?Q?Norbert_P=FCrringer?=

    How to convert to an object of a certain type?

    Hello,

    Imagine, that I've got a string variable containing a value of each
    possible value type (string, int32, double, ...). Now I want to
    convert the string to an object of the right type, where the correct
    type is given by a Type variable.

    So given is:
    string strValue;
    Type typeValue;

    And I want to call something like
    object value = Convert.ToType( strValue, typeValue);

    Is there a simple way to do that?

    Thank you,
    Norbert
  • Marc Gravell

    #2
    Re: How to convert to an object of a certain type?

    See below; Marc

    string src = "12345";
    Type dest = typeof(int);

    // simple
    int value1 = (int)Convert.Ch angeType(src, dest);

    // more versatile but more complex
    // (and you might need to look at src->ConvertTo)
    int value2 = (int)TypeDescri ptor.GetConvert er(dest).Conver tFrom(src);

    Comment

    • =?ISO-8859-1?Q?Norbert_P=FCrringer?=

      #3
      Re: How to convert to an object of a certain type?

      Hi Marc,
      string src = "12345";
      Type dest = typeof(int);
      >
      // simple
      int value1 = (int)Convert.Ch angeType(src, dest);
      >
      // more versatile but more complex
      // (and you might need to look at src->ConvertTo)
      int value2 = (int)TypeDescri ptor.GetConvert er(dest).Conver tFrom(src);
      That's good, thank you. Do you have an idea how to convert an array of
      string into an array of a certain type given by a Type variable.
      ChangeType only works for non array variables.

      Thank you,
      Norbert

      Comment

      • Marc Gravell

        #4
        Re: How to convert to an object of a certain type?

        If you know the destination type at compile-time (perhaps via generics),
        the following works:

        string[] data = {"12345", "3154", "15012"};
        // C# 2 (VS2005)
        int[] values1 = Array.ConvertAl l<string, int>(data,
        delegate(string value)
        { // of your chosen method from last post...
        return int.Parse(value );
        });
        // C# 3 (VS2008)
        int[] values = Array.ConvertAl l(data, value =>
        int.Parse(value ));

        Again - you would be able to use this with generics (T[], etc). If you
        don't know the type (and generics aren't available), you could either
        use an object[], or ues Array.CreateIns tance to create an array (of
        cited type), then loop over it setting values.

        My first choice would be: refactor the code so that you can use
        generics. Hard to say "how" without more detail...

        Marc

        Comment

        • =?ISO-8859-1?Q?Norbert_P=FCrringer?=

          #5
          Re: How to convert to an object of a certain type?

          Hi Marc,
          Again - you would be able to use this with generics (T[], etc). If you
          don't know the type (and generics aren't available), you could either
          use an object[], or ues Array.CreateIns tance to create an array (of
          cited type), then loop over it setting values.
          >
          My first choice would be: refactor the code so that you can use
          generics. Hard to say "how" without more detail...
          I would like use generics, but how???

          I've got a Type variable, e.g.

          Type type = typeof(System.I nt32);

          How can I instantiate a generic list using that type variable?

          List<typelist = new List<type>();

          does not work. The compiler needs something like that:

          List<Int32list = new List<Int32>();

          That's static. I need a dynamic way. Any idea?

          Kind regards,
          Norbert

          Comment

          • Ben Voigt [C++ MVP]

            #6
            Re: How to convert to an object of a certain type?

            Marc Gravell wrote:
            If you know the destination type at compile-time (perhaps via
            generics), the following works:
            >
            string[] data = {"12345", "3154", "15012"};
            // C# 2 (VS2005)
            int[] values1 = Array.ConvertAl l<string, int>(data,
            delegate(string value)
            { // of your chosen method from last post...
            return int.Parse(value );
            });
            // C# 3 (VS2008)
            int[] values = Array.ConvertAl l(data, value =>
            int.Parse(value ));
            >
            Again - you would be able to use this with generics (T[], etc). If you
            don't know the type (and generics aren't available), you could either
            use an object[], or ues Array.CreateIns tance to create an array (of
            cited type), then loop over it setting values.
            You could do this, however I would expect it to be very slow because it has
            to re-test the destination type and re-plan the conversion for each element.

            Array dest = Array.CreateIns tance(t, src.Length);
            Array.ConvertAl l<string, object>(delegat e (string value) {
            Convert.ChangeT ype(value, t); }).CopyTo(dest, src.Length);
            >
            My first choice would be: refactor the code so that you can use
            generics. Hard to say "how" without more detail...
            >
            Marc

            Comment

            • Marc Gravell

              #7
              Re: How to convert to an object of a certain type?

              You can use reflection to invoke the generic method dynamically:

              using System;
              using System.Componen tModel;
              using System.Reflecti on;
              static class Program
              {
              static void Main()
              {
              string[] values = {"12345", "123", "5142"};
              foreach (int value in CreateData(type of(int), values))
              {
              Console.WriteLi ne(value);
              }
              }

              // get the method-template (i.e. this points to CreateData<T>, but
              without the "T" yet)
              private static readonly MethodInfo genericMethod =
              typeof(Program) .GetMethod("Cre ateData", BindingFlags.No nPublic
              | BindingFlags.St atic,
              null, new Type[] { typeof(string[]) }, null);

              // actually returns an array of the correct type, but arrays are
              covariant
              static Array CreateData(Type destinationType , string[] values)
              {
              // invoke the generic method (after supplying a specific "T")
              object[] args = { values };
              return
              (Array)genericM ethod.MakeGener icMethod(destin ationType).Invo ke(null, args);
              }
              static T[] CreateData<T>(s tring[] values)
              {
              TypeConverter converter = TypeDescriptor. GetConverter(ty peof(T));
              return Array.ConvertAl l<string, T>(values, delegate(string val)
              {
              return (T)converter.Co nvertFrom(val);
              });
              }
              }

              Comment

              Working...