Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

Ruby Module equivalent in C#?

Hello!

A couple of months ago I made a Ruby program containing a module to hold all the common operations I was doing throughout the program.
Now I'm switching to C# and I would like to know how I could achieve the same effect.

I've been told that namespaces were the C# equivalent of Ruby modules. However, I can't seem to use them the same way.
I would like it to hold variables and methods outside of classes and be able to interact with them as I see fit.
Maybe I'm wrong with namespaces and I should probably use static classes, but as far as I know static classes can only content static stuff which doesn't work for me.

Any thoughts about this?

Thank you very much,
- Dargor
 
Create static methods.

Code:
namespace MyNamespace

{

        class MyClass

        {

                public static int AddNumbers(int num1, int num2)

                {

                        return num1 + num2;

                }

        }

}

Then you can use the methods like you would a static method in Ruby:

Code:
int someNumber = MyClass.AddNumbers(4, 5);

You can make the class static as well, depending on your need, but static methods allows you to create instances of the class, as well as create static calls for other classes. Just keep in mind when mixing static and non-static methods in the same class, the static members are totally independent of any non-static variable in the same class, and attempt to reference one will throw an exception, so if you need to use non-local variables in your static methods, they need to be static as well.
 
Juan J. Sánchez":30xamoa9 said:
You could also create libraries and include them at the top of the file.

http://www.learncpp.com/cpp-tutorial/a1 ... libraries/

I don't think that's exactly the same thing he means. Thats just a article about importing DLLs, which consists of nothing more than adding a reference and importing like you would any other namespace. All the rules of a static and non-static class/method remain the same, whether it is in an external file or in the same one.
 
Thank you for the help guys.
ForeverZer0's method is exactly what I was looking for. It works like a charm.

Thanks a lot!
- Dargor
 

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top