I would like to convert a System.Type
to Generic Type definition, so I can use it to call Generic methods. Basically the reverse of typeof
.
Example (i used "classof" where I would need the real solution so that you see where I got a problem, as classof is not a real .NET method):
public class BaseAppContext {
private Type settingsType;
public Type SettingsType
{
get { return this.settingsType; }
set { this.SettingsType = value; }
}
public void MyFunction() {
MyStaticClass.GetData<classof(this.SettingsType)>();
}
}
Just some more information why I am using this strange way to handle the problem. BaseAppContext is a class that is refered to by a lot of other classes. If I would would make it Generic that would mean a lot of other parts of the code would change, which I don't want. I am writing a framework, so I would like for the framework to input the type once, and the developers can just use the provided functions without having to deal with the type everytime they try to call a method.
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.
You can create an instance of generic classes by specifying an actual type in angle brackets. The following creates an instance of the generic class DataStore . DataStore<string> store = new DataStore<string>(); Above, we specified the string type in the angle brackets while creating an instance.
In C#, the “T” parameter is often used to define functions that take any kind of type. They're used to write generic classes and methods that can work with any kind of data, while still maintaining strict type safety.
This won't be possible, since SettingsType
is set at runtime and code between <>
is compiled.
You can create an instance of your type like this:
var type = Type.GetType(SettingsType);
var inst = Activator.CreateInstance(type);
and cast inst
to an interface or base class.
Since you're using a static class, rich's answer is better.
This is fundamentally impossible.
Generics form compile-time types; you cannot create a compile-time type from a type known only at runtime.
Instead, you need to use reflection, or use a different design (eg, a non-generic method).
To achieve this, you'll need to use reflection:
public void MyFunction() {
var method = typeof(MyStaticClass).GetMethod("GetData").MakeGenericMethod(SettingsType);
method.Invoke(null, null);
}
However, I would not recommend doing this and would instead advise redesigning your solution. Using reflection means that you miss out on all the lovely compile time safety that the language provides. This generally leads to more brittle, less maintainable code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With