Thursday, September 27, 2012

Beginner in C#: Helper methods

What's a helper method?

Well, a helper method is a statement that carries with it a big or small piece of code, created by you, to execute them easily in your program

Why to use helper methods in C#?

Using helper method can help you to save time, for example if you need to get the factorial of an integer more than one time in your code, it's better for  you to create a method and call it something like getFact(uint n), with a parameter an unsigned integer.

What are the types of helper methods?

  1. Methods that don't return a value (of type void).
  2. Methods that returns value (of type int, string, Button, bool, etc... it depends on your needs)

Example on C# helper methods:

Number factorial function C#

You can do this function in two ways , using a recursive method or not.

Recursive method C#:

        public static uint getFact(uint n)
            if (n <2) 
                return 1;
           //you don't have to use 'else' here
            return n * getFact(n - 1);

Non-recursive method C#:

        public static uint getFact(uint n)
            uint ans=1;
            for (uint i = 2; i <= n; i++)
                ans *= i;
            return ans;
So now you are ready to create your own helper methods! have a question? Comment on this post.