Jump to content
  • Advertisement
Sign in to follow this  
Wibbs

Passing a static class into a function (C#)

This topic is 2905 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey all,

I've run into a problem with some c# code I am writing. I have a function which accepts an object as a parameter and then uses reflection to get information about the methods of the instance, and this is working well. However, I've now run into a situation where I need to pass in a static class and I can't work out how to do it. I would be grateful if anyone could point me in the right direction.

Thanks,

Phil

Share this post


Link to post
Share on other sites
Advertisement
Rather than pass an instance of a class, I'd pass a Type and an optional instance. You could implement two helper methods, one that takes an instance (as I presume you currently do) and another that takes a type. Both could split the type and the instance and pass this information to the main method:

// Master function.
static void SomeFunction(Type type, object instance) {
Console.WriteLine("Type is '{0}', instance is '{1}'.", type, instance);
}

// Used for instances.
public static void SomeFunction<T>(T instance) {
SomeFunction(typeof(T), instance);
}

// Used for static types.
public static void SomeFunction(Type type) {
SomeFunction(type, null);
}

static void Main(string[] args) {
SomeFunction(1234); // Type is 'System.Int32', instance is '1234'.
SomeFunction("Hello"); // Type is 'System.String', instance is 'Hello'.
SomeFunction(typeof(Console)); // Type is 'System.Console', instance is ''.
}

Share this post


Link to post
Share on other sites
The simple answer is you don't.

You have to use types. But of course, that means that you can't pass an instance of the class. You really can't treat a static class like an instance class.

theTroll

Share this post


Link to post
Share on other sites
Hey all

Thanks for the quick responses. I've worked out how to do it with the approach suggested by benryves which is great. What I'm actually doing is using function attributes to automatically register functions with LuaInterface, and although I have the reflection bit working well now, I now can't work out how to register fuctions from static classes with LuaInterface as the RegisterFunction method provided requires an object instance as one of it's parameters. I've posted seperately on this in the scripting subforum, and thanks again for the help.

Phil

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!