How can I put the type of a variable in a method parameter as something is defined by a class variable? For example:
class MyClass {
private Type _type;
public MyClass(Type type) {
_type = type;
}
public void SomeMethod(_type param) { //... }
public _type OtherMethod() {}
}
So, the idea is, I could set a dynamic type to a variable in the class, and use the Type variable as the type for other objects.
Is it possible to do this in C#?
Edit:
I decided to make my question clearer and explain on why I am asking for such a feature. I have tried Generics. The problem with generics, however, is that I have to declare the type for the class every time I refer to an object of that class like: MyClass<TSomeType> param
In my scenario, I have a List<MyClass> dataList that contains MyClass. If I had a generic on MyClass, then dataList has to be List<MyClass<TSomeType>>. In this case, I am stuck because the list can only consist of MyClass<TSomeType>. I cannot have other kinds of Types once I declared the type for the whole class. This is the reason why I want to know if there is a more dyanmic way of declaring a Type, like I could store the type of a class to a variable, and then use this variable like a class type.
No. What would the compiler do with a
MyClass? It couldn’t possibly know whether a method call was valid or not.You can use generics instead though:
At this point, when the compiler sees a
MyClass<string>it knows thatSomeMethod("foo")is valid, butSomeMethod(10)isn’t.If you really won’t know the type until execution time, then you might as well just use
object:… and potentially do execution-time checking against a
Typeif you really want to.