Sign in to follow this  

C# - defining a generic function 'type'

Recommended Posts

I have a function: void Foo<T>(). This is a generic function. It is called in a few locations in the code. Let us pretend type T is the level I want to play. So: Foo<Level_1>() does something to level 1, etc... For a given execution of code, I only want to test a single level. This means all of the type T's in my code need to be the same for a given execution. Currently, I have to do a find/replace all every time I switch the level for testing purposes. In C/C++, this would be a simple job for macros: #define MY_LEVEL Level_1 Foo<MY_LEVEL>() How can I get the same behavior in C#? Thanks.

Share this post

Link to post
Share on other sites
Judging by that horrible mix of macros and templates, I'd say you have a design problem. I also noticed Foo doesn't take any parameters, seems you would want it to know what level to work on based on type.

What you should have is a class(I'll call it Level) that contains code common to all your level files. Store an instance of it somewhere and change Foo to something like:

void Foo( Level level ){}

When you want to test a different level just change the file the level is loaded from:

Level level = new Level( "" );
Foo( level );
Bar( level );

There's no real need to use generics here either. Each level should not require it's own class. What if your game has 100 levels, are you going to make Level_1 all the way to Level_100?

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this