Reputation: 201
I have variable in my class with type of 'Type':
class A
{
public static Type MyType;
}
And I declared this variable with anywhere construction. Example:
A.MyType = b.GetType();
First problem: I need declare new variable with type stored in MyType.
<MyType> myValue = new <MyType>;
Second problem: I need a function that indicates whether reducible to each other variables of the 'Type'.
Upvotes: 2
Views: 3593
Reputation: 1504162
First problem: I need declare new variable with type stored in MyType.
You can't do this, basically.
Variable types need to be known at compile-time. You can't declare a variable using a type which is only known at execution time. You can get some of the way there using generics:
public class Foo<T>
{
private T value;
}
You can even add a constraint to require that T
has a parameterless constructor which you can then call:
public class Foo<T> : new()
{
private T value = new T();
}
... and you could create a Foo<T>
when you only know the type of T
at execution time using reflection:
Type genericDefinition = typeof(Foo<>);
Type constructed = genericDefinition.MakeGenericType(A.MyType);
object instance = Activator.CreateInstance(constructed);
... but it will get messy pretty quickly. You haven't told us anything about what you're actually trying to achieve, so it's hard to suggest an alternative - but if you can possibly redesign to avoid this, I would.
Second problem: I need a function that indicates whether reducible to each other variables of the 'Type'
It's possible that you're looking for Type.IsAssignableFrom
, but it's not clear...
Upvotes: 8