Reputation: 15638
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.
Upvotes: 2
Views: 371
Reputation: 82096
I think what yor looking for here is Generics - This would give you what you are after plus the benefit of compile-time type safety.
public MyClass<T>
{
public void SomeMethod(T param)
{
...
}
public T OtherMethod()
{
...
}
}
Usage
var intClass = new MyClass<int>();
intClass.SomeMethod("10"); // would cause a compile error
intClass.SomeMethod(10); // would compile ok
string result = intClass.OtherMethod(); // would cause a compile error
int result = intClass.OtherMethod(); // would compile ok
Upvotes: 2
Reputation: 1499950
Is it possible to do this in C#?
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:
class MyClass<T>
{
public void SomeMethod(T param) { ... }
public T OtherMethod() { ... }
}
At this point, when the compiler sees a MyClass<string>
it knows that SomeMethod("foo")
is valid, but SomeMethod(10)
isn't.
If you really won't know the type until execution time, then you might as well just use object
:
class MyClass
{
public void SomeMethod(object param) { ... }
public object OtherMethod() { ... }
}
... and potentially do execution-time checking against a Type
if you really want to.
Upvotes: 5