I have a object:
ExampleClass ex = new ExampleClass();
And:
Type TargetType
I would like to cast ex to type described by TargetType like this:
Object o = (TargetType) ex;
But when I do this I get:
The type or namespace name 't' could
not be found
So how to do this? Am I missing something obious here?
Update:
I would like to obtain something like this:
public CustomClass MyClassOuter
{
get
{
return (CustomClass) otherClass;
}
}
private otherClass;
And because I will have many properties like this I would like do this:
public CustomClass MyClassOuter
{
get
{
return (GetThisPropertyType()) otherClass;
}
}
private SomeOtherTypeClass otherClass;
Context:
Normally in my context in my class I need to create many properties. And in every one replace casting to the type of property. It does not seem to have sense to me (in my context) because I know what return type is and I would like to write some kind of code that will do the casting for me. Maybe it's case of generics, I don't know yet.
It's like I can assure in this property that I get the right object and in right type and am 100% able to cast it to the property type.
All I need to do this so that I do not need to specify in every one property that it has to "cast value to CustomClass", I would like to do something like "cast value to the same class as this property is".
For example:
class MYBaseClass
{
protected List<Object> MyInternalObjects;
}
class MyClass
{
public SpecialClass MyVeryOwnSpecialObject
{
get
{
return (SpecialClass) MyInteralObjects["MyVeryOwnSpecialObject"];
}
}
}
And ok - I can make many properties like this one above - but there is 2 problems:
1) I need to specify name of object on MyInternalObjects but it's the same like property name. This I solved with System.Reflection.MethodBase.GetCurrentMethod().Name.
2) In every property I need to cast object from MyInternalObjects to different types. In MyVeryOwnSpecialObject for example - to SpecialClass. It's always the same class as the property.
That's why I would like to do something like this:
class MYBaseClass
{
protected List<Object> MyInternalObjects;
}
class MyClass
{
public SpecialClass MyVeryOwnSpecialObject
{
get
{
return (GetPropertyType()) MyInteralObjects[System.Reflection.MethodBase.GetCurrentMethod().Name];
}
}
}
And now concerns: Ok, what for? Because further in my application I will have all benefits of safe types and so on (intellisense).
Second one: but now you will lost type safety in this place? No. Because I'm very sure that I have object of my type on a list.
See Question&Answers more detail:
os