I’m trying to create a function in C# which will allow me to, when called, return a reference to a given class type. The only types of functions like this that I have seen are in UnrealScript and even then the functionality is hard coded into its compiler. I’m wondering if I can do this in C#. Here’s what I mean (code snippet from UnrealScript source):
native(278) final function actor Spawn ( class<actor> SpawnClass, optional actor SpawnOwner, optional name SpawnTag, optional vector SpawnLocation, optional rotator SpawnRotation );
Now in UScript you would call it like this…
local ActorChild myChildRef; //Ref to ActorChild which Extends 'actor' myChildRef = Spawn(class'ActorChild' ...); //rest of parameters taken out myChildRef.ChildMethod(); //method call to method existing inside class 'ActorChild'
Which will return a reference to an object of class ‘ActorChild’ and set it to variable ‘myChildRef.’ I need to do something similar within C#.
I’ve looked into Generics but it seems that to use them, I need create an instace of the class where my function lies and pass the ‘generic’ parameter to it. This isn’t very desirable however as I won’t need to use the ‘Spawn’ function for certain classes but I would still need to add the generic parameter to the class whenever I use it.
I guess a simplified question would be, how can I return a type that I do not know at compile time and when the different classes could be far too many to trap.
Pseudo-Code (sticking to UScript class names, i.e. Actor):
//Function Sig public class<Actor> Create(class<Actor> CreatedClass) { return new CreatedClass; } //Function call ActorChild myChild = Create(class'ActorChild');
Any ideas?
EDIT: I would like to avoid explicit typecasts that would occur from the class calling Created. If I can typecast to the desired object within the Created method and return the ‘unknown type’ whatever that may be, I would be extremely happy.
EDIT 2: Thanks for your answers.
Rather than use a generic class, use a generic method:
Having said that, I assume you want to do more than just blindly create an instance, otherwise you could just call
new MyClass()yourself.