Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Methods in C# - Is this correct? [closed]

Tags:

c#

.net

windows

I have been delving into C# recently, and I wonder if anyone would mind just checking my write up on it, to make sure it is accurate?

Example: Calculating factorials with the use of an Extension method.

For example if you wanted to extend the int type you could create a class e.g. NumberFactorial and create a method e.g. Static Void Main, that calls e.g. int x = 3 Then prints out the line (once its returned from the extension method)

Create a public static method that contains the keyword "this" e.g. this int x perform the logic and the parameter is then fed back to the inital method for output.

The code is below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 3;
            Console.WriteLine(x.factorial());
            Console.ReadLine();
        }
    }
    public static class MyMathExtension
    {
        public static int factorial(this int x)
        {
            if (x <= 1) return 1;
            if (x == 2) return 2;
            else
                return x * factorial(x - 1);
        }
    }
}
like image 267
Michael Avatar asked May 17 '11 17:05

Michael


2 Answers

It certainly looks accurate. However, I'm wondering why you would care to have two exit conditions when only one is really needed. Also, if you made the code, you should easily be able to unit test it to make sure it's accurate.

like image 42
Tejs Avatar answered Oct 01 '22 12:10

Tejs


Yes, that is correct.

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

You can find out more about extension methods here and here

like image 162
Robert Greiner Avatar answered Oct 01 '22 10:10

Robert Greiner