Mahdi Ahmadi
Mahdi Ahmadi

Reputation: 441

Cast from unknown type in c#

I have a object that contain a value in string and a origin Type that is in a field.

class myclass
{
   public string value;
   public Type type;
}
myclass s=new myclass();
s.value = "10";
s.type = typeof(int);
Type tt = s.type;
row.Value[ind]= s[0].value as tt; //i have error here

How can i cast an value by that's type.

Upvotes: 3

Views: 10096

Answers (2)

Manish Mishra
Manish Mishra

Reputation: 12375

Basically your scenario is that you want to type cast with the type stored in a variable. You can only do that at runtime like this :

    myclass s=new myclass();
    s.value = "10";
    s.type = typeof(int);

    var val = Convert.ChangeType(s.value, s.type);

but since the conversion is done at runtime, you cannot store the variable val in any integeral collection i.e. List<int> or even you cannot do int another = val, coz at complie time, the type is not known yet, and you will have compilation error, again for same obvious reason.

In a little complex scenario, if you had to typecast to a User-Defined dataType and you wanted to access its different properties, you cannot do it as is. Let me demonstrate with few modifications to your code :

class myclass
{
    public object value;
    public Type type;
}

and you have another:

    class myCustomType
    {
        public int Id { get; set; }
    }

now you do :

 myclass s = new myclass();
 s.value = new myCustomType() { Id = 5 };
 s.type = typeof(myCustomType);
 var val = Convert.ChangeType(s.value, s.type);

now if you do val.Id, it won't compile. You must retrieve it either by using dynamic keyword or by reflection like below:

 var id = val.GetType().GetProperty("Id").GetValue(val);

you can iterate over all the available properties of your customType (class) and retrieve their values.

for retrieving it through dynamic keyword, directly do this:

dynamic val = Convert.ChangeType(s.value, s.type);
int id = val.Id;

and compiler won't cry. (Yes there won't be any intellisense though)

Upvotes: 13

Alioza
Alioza

Reputation: 1770

Try this:

row.Value[ind] = Convert.ChangeType(s.value, tt);

Upvotes: 1

Related Questions