Chris
Chris

Reputation: 925

casting to an unknown type reflection in C#

the problem I am currently having is that I am trying to cast to an unknown type and I receive this message from the following code:

The type or namespace name 'thistype' could not be found (are you missing a using directive or an assembly reference?)

String thistype = null;

for (int i = 0; i < items.Length; i++)
{

    thistype =  typeof(BugManagerQueryOptions).GetProperty(items[i].ToString()).PropertyType.Name; 
    typeof(BugManagerQueryOptions).GetProperty(items[i].ToString()).SetValue(currentSearch,(thistype)properties[i], null);

}

If you need any more information just ask and any help would be appreciated, thanks. - Chris

Upvotes: 2

Views: 979

Answers (2)

Chris
Chris

Reputation: 925

For any future reference, this is the (very sloppy) way of doing what I was trying to do, I will be improving on this but I thought I should leave this here for anyone else.

            thistype =  typeof(BugManagerQueryOptions).GetProperty(items[i].ToString()).PropertyType.FullName;

            if (thistype == "System.String")
            {
                 typeof(BugManagerQueryOptions).GetProperty(items[i]).SetValue(currentSearch, properties[i], null);
            }
            else if (thistype == "System.Nullable`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
            {

                long number = Int64.Parse(properties[i]);
                typeof(BugManagerQueryOptions).GetProperty(items[i]).SetValue(currentSearch, number, null);

            }
            else if (thistype == "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
            {

                int number = Int32.Parse(properties[i]);
                typeof(BugManagerQueryOptions).GetProperty(items[i]).SetValue(currentSearch, number, null);

            }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503140

You don't need to cast at all, assuming the value of properties[i] is already actually the right type:

for (int i = 0; i < items.Length; i++)
{
    typeof(BugManagerQueryOptions).GetProperty(items[i].ToString())
                                  .SetValue(currentSearch, properties[i], null);
}

If you were trying to invoke a user-defined conversion (e.g. from XElement to String) then that's a lot more complicated.

Upvotes: 4

Related Questions