Well, the answer is "yes, you
could do that, but
why would you
want to do that ?" Let me see if I can "talk you out of that."
using System;
using Feb1_ExtendClass;
namespace Feb1_ExtendClass
{
public class ClassA
{
public int MethodA(int value)
{
Console.Write("Raised in MethodA");
return value + value;
}
public int MethodB(int value)
{
Console.Write("Raised in MethodB");
return value/2;
}
}
}
namespace ExtensionMethods
{
public static class ExtendsA
{
public static ClassA MethodB(this ClassA a)
{
Console.WriteLine("Raised in Extension MethodB");
return a;
}
public static ClassA MethodA(this ClassA a)
{
Console.WriteLine("Raised in Extension MethodA");
return a;
}
}
}
Put to the test in a WinForms project:
using System;
using System.Windows.Forms;
using ExtensionMethods;
namespace Feb1_ExtendClass
{
public partial class Form1 : Form
{
public Form1() {InitializeComponent();}
private void button1_Click(object sender, EventArgs e)
{
ClassA newA = new ClassA();
var whatever = newA.MethodA().MethodB();
}
}
}
What I hope you can see in this strange example is that:
1. there's no point writing an Extension Method for a Class if the method doesn't change
something in the Class instance it operates on.
With rare exceptions (damn if I can think of any), you should:
1. write Extension methods that take parameters, and return some useful results.
Note: I deliberately made this example as weird as possible by putting methods in ClassA with the same names as the Extension Methods, but with different structure, for the purpose of showing the
semantic independence of Extension Methods from Class Methods. This is a practice I would never hope to see done in actual code !