0

I have an input string which could be int,string,float or any of the data type.

Now I want to do some thing like:

string stringType= "Int";  
Type dataType = Type.GetType(stringType);

string someValue = 20;

int newValue = (dataType)someValue ;

Edit:

I will receive both type and value as string and need to cast them run time.

 public void StoreWorkData(List<TypeAndvalue> workDataPropertyDetails)
        {
            foreach (var property in workDataPropertyDetails)
            {
                string stringType = property.dataType;
                //Want to create the type in run time     
                Type dataType = Type.GetType(stringType);

                //Assign the value to type created above    
                dataType newValue = (dataType)property.Value;
            }
        }
10
  • You can use switch statement. Commented Feb 9, 2016 at 16:30
  • 1
    Can you provide a proper piece of code that actually compiles, and explain in English what exactly you want this code to do? Can you also show how you are supposed to call it and use the returned value? Take a look at the static Convert class, anyway. Commented Feb 9, 2016 at 16:33
  • So the user is inputting both the type and the value (both as strings, of course), and you want a variable of that type with that value? Commented Feb 9, 2016 at 16:33
  • 1
    @CodeCaster: Very much so, and begs the question "why". The effectiveness of it is going to depend heavily on its intended use. Commented Feb 9, 2016 at 16:34
  • 1
    @Simsons: How is this going to be used? The current answer below should do the trick, but also boxes the value into an object (which may be simply the reality of what you're trying to do here). Commented Feb 9, 2016 at 16:40

3 Answers 3

3

Ok, first we create a method to parse a string to object:

static object Parse(string typeName, string value)
{
    var type = Type.GetType(typeName);
    var converter = TypeDescriptor.GetConverter(type);

    if (converter.CanConvertFrom(typeof(string)))
    {
        return converter.ConvertFromInvariantString(value);
    }

    return null;
}

Inside the method you post you can call it:

public void StoreWorkData(List<TypeAndvalue> workDataPropertyDetails)
{
    foreach (var property in workDataPropertyDetails)
    {
        dynamic newValue = Parse(property.dataType, property.Value);

        SomeMethod(newValue);
    }
}

You can have different SomeMethod methods with different argument types:

void SomeMethod(int value);
void SomeMethod(double value);
...

The dynamic type do the magic to call the right method (if present). For more info take a look at this

Sign up to request clarification or add additional context in comments.

Comments

2

Type.GetType, used correctly, will give you a Type instance which itself can be used to create an instance of that type via something like Activator.CreateInstance.

string desiredTypeName = /* get the type name from the user, file, whatever */
Type desiredType = Type.GetType(desiredTypeName);
object instance = Activator.CreateInstance(desiredType);

If desiredTypeName is "System.String", then instance will be a string. If it's "YourNamespace.YourType" then instance will be a YourType. And so on.

If you require the instance to be constructed with parameters, there are overloads of CreateInstance that allow you to specify constructor parameters.

If the values of your constructor parameters are also given to you as strings, you can use the methods of the Type object on the desiredType instance to get the available constructors and determine their required parameter types and parse the strings into those types.


Note that this method will limit you to using the interface of System.Object for the instance at compile-time; naturally you will not be able to write code that naturally accesses the instance as the runtime type, because that type is not known until runtime. You can switch on the type name and downcast instance if you want, but at that point you did a bunch of work (all that Activator junk) for effectively nothing.

Also note that Activator is not the fastest way to create instances of types determined at runtime; it's just the simplest.

Comments

0

Activator.CreateInstance can be used to create instance of Type at run time

string stringType= "MyType";  
Type dataType = Type.GetType(stringType);
dynammic instance = Activator.CreateInstance(dataType);

To support casting from string you have to implement below method in your type

public static explicit operator MyType(string s)
{
   // put logic to convert string value to your type
    return new MyType
    {
        value = s;
    };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.