Reputation: 179
i wonder if there is a way to cast to exact type using system.reflection so that you will avoid doing explicit cast such as
(System.DateTime)
for example
Assuming i would have a Dictionary such as
Dictionary<propName, Dictionary<object, Type>>
and assuming i iterate over an object props list
foreach (var prop in @object.GetType().GetProperties())
{
object propValue = propInfo.GetValue(@object, null);
string propName = propInfo.Name;
Dictionary<object, Type> typeDictionary = new Dictionary<object, Type>();
Type propType = propInfo.GetValue(@object, null).GetType();
typeDictionary[propValue ] = propType ;
propsDictionary[propInfo.Name] = propValue;
}
I would like to do something like , cast to exact type using something like
// this part is only for guidelines
// it should obtain the exact Type
// ... but it returns a string of that type Namespace.Type
Type exactType = Dictionary[enumOfPropName][someValue]
// this part should know the exact type Int32 for example and cast to exact
var propX = (exactType)someValue
Is there any way of doing such thing and if so how can i obtain this? Also most of this code is just a guideline, an idea so please don't take it likely. Thank you all.
Upvotes: 0
Views: 4171
Reputation: 4014
Once you know the type:
var x = 22;
var type = typeof(Int32);
var propX = Convert.ChangeType(x, type);
Or in your case:
object thing = 32;
var lookup = new Dictionary<string, Dictionary<object, Type>>();
lookup.Add("Test", new Dictionary<object, Type>());
lookup["Test"].Add(thing, typeof(Int32));
var propX = Convert.ChangeType(thing, lookup["Test"][thing]);
Caveats with this approach: Convert.ChangeType: For the conversion to succeed, value must implement the IConvertible interface...
Upvotes: 4
Reputation: 781
If I understand your question, you want to convert an object (in an object
typed variable) to its actual type you have extracted thorough reflexion. If so, I beleive Convert.ChangeType
could be of help to you. You can use it like this :
var propX = Convert.ChangeType(someValue, exactType);
I am pretty casting requires you to know the type at compile-time, which is why you cannot cast with a Type
variable (since it's only known at runtime).
Upvotes: 0
Reputation: 29233
The conclusion here is that it's not possible to have a statically typed variable that matches the exact type of an arbitrary object instance, because doing so would require information that is not available yet.
As a workaround, consider making the variable dynamic
and see what you can do from there.
Upvotes: 5
Reputation: 669
You will need to implement an implicit operator on the target class to the type you want
class Program
{
static void Main(string[] args)
{
var a = new A() { property = "someValue" };
string obj = (string)teste;
}
}
class A
{
public string property { get; set; }
public static implicit operator string(A t)
{
if (t == null)
return null;
return t.property;
}
}
Upvotes: -1