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);
}
}
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With