0
Type type1 = Type.GetType("System.Int32");
string test = "test";

please let me know how to convert the test to an object based on type1 object. And it should fail or return null as the given string cannot be converted to int.

This for validation purpose.

Carlos Muñoz
  • 17,397
  • 7
  • 55
  • 80
shiv455
  • 7,384
  • 19
  • 54
  • 93
  • 1
    What are you really trying to do? If it is just to see if a string is an int then Boas' answer is correct. This sounds like an X-Y problem – Sayse Jul 28 '14 at 07:13
  • Why don't you know the type at compile time? That seems to be the real problem. – Tim Schmelter Jul 28 '14 at 07:26

2 Answers2

2

I'm not quite sure if i understand you right.

if you want to safely convert a string to int see

int result;
bool wasConverted;
wasConverted = int.TryParse(test,out result)

For more generic conversion ahve a look at the ConvertClass.

For Example Convert.ChangeType but there you would have to handle exceptions your own way.

public object SafeConvertChangeType(object value,Type targetType)
      {
      object result ;
      try {
           result = Convert.ChangeType(value, targetType);
      }
      catch (FormatException)
      catch (InvalidCastException) {
           result = null;
      }
return result;
}

you can that call the method this was:

var result = SafeConvertChangeType("Foo",typeof(int32));

You may also have a loot at this post: Test if Convert.ChangeType will work between two types. It points out that there is no "ConversionCheck" Api. So I assumed you would need that exception catch

Community
  • 1
  • 1
Boas Enkler
  • 12,264
  • 16
  • 69
  • 143
1

You can use Convert.ChangeType:

Type type1 = Type.GetType("System.Int32");
string test = "test";
object newObject = Convert.ChangeType(test, type1);
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325