473,396 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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
Jun 27 '08 #1
6 2806
See below; Marc

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

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

// more versatile but more complex
// (and you might need to look at src->ConvertTo)
int value2 = (int)TypeDescriptor.GetConverter(dest).ConvertFrom (src);
Jun 27 '08 #2
Hi Marc,
string src = "12345";
Type dest = typeof(int);

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

// more versatile but more complex
// (and you might need to look at src->ConvertTo)
int value2 = (int)TypeDescriptor.GetConverter(dest).ConvertFrom (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
Jun 27 '08 #3
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.ConvertAll<string, int>(data,
delegate(string value)
{ // of your chosen method from last post...
return int.Parse(value);
});
// C# 3 (VS2008)
int[] values = Array.ConvertAll(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.CreateInstance 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
Jun 27 '08 #4
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.CreateInstance 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.Int32);

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
Jun 27 '08 #5
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.ConvertAll<string, int>(data,
delegate(string value)
{ // of your chosen method from last post...
return int.Parse(value);
});
// C# 3 (VS2008)
int[] values = Array.ConvertAll(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.CreateInstance 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.CreateInstance(t, src.Length);
Array.ConvertAll<string, object>(delegate (string value) {
Convert.ChangeType(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

Jun 27 '08 #6
You can use reflection to invoke the generic method dynamically:

using System;
using System.ComponentModel;
using System.Reflection;
static class Program
{
static void Main()
{
string[] values = {"12345", "123", "5142"};
foreach (int value in CreateData(typeof(int), values))
{
Console.WriteLine(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("CreateData", BindingFlags.NonPublic
| BindingFlags.Static,
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)genericMethod.MakeGenericMethod(destination Type).Invoke(null, args);
}
static T[] CreateData<T>(string[] values)
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
return Array.ConvertAll<string, T>(values, delegate(string val)
{
return (T)converter.ConvertFrom(val);
});
}
}
Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Arvid Andersson | last post by:
Hello, I need to convert a string to a number, but the string can contain +,-,* and / as well as parenthesis. For example, if I have the string "30/(6+9)" I would like a function that returned the...
1
by: phancey | last post by:
I am trying to invoke a web service method dynamically. I have created a generic function that takes a method name, string of parameters and calls the web method using System.Reflection: ...
8
by: CA | last post by:
Hi, I have a function where I would like to test whether an object is of a certain type. Here is my code so far. public bool HasValidType(Type t, object val) { try { if (t==typeof(double))
4
by: Ken Varn | last post by:
I have an unknown numeric Type object passed into a function. I want to run a conversion on a string to convert the string to that Type object and return an object of that type. Is there some way...
7
by: Jim Bancroft | last post by:
Hi everyone, A basic one here, I think. I haven't found the pattern yet, but sometimes when I cast a variable to another type using the "C" style cast operator the compiler refuses to play...
10
by: Nikolay Petrov | last post by:
How can I convert DOS cyrillic text to Unicode
2
by: Christophe | last post by:
class A {} class B {} interface MyInterface { void method(A a); void method(B b); }
3
by: mrajanikrishna | last post by:
Hi Friends, I am accepting a number from the user entered in a textbox. I want to assign to a variable in my code and assignt this to that variable. double num1 = (double)txtNum1.text; ...
9
by: Marco Nef | last post by:
Hi there I'm looking for a template class that converts the template argument to a string, so something like the following should work: Convert<float>::Get() == "float"; Convert<3>::Get() ==...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.