With C# 3.0, I know you can extend methods using the 'this' nomenclature.
I'm trying to extend Math.Cos(double radians) to include my new class. I know that I can just create a "Cos" method in my existing class, but I'm just interested in seeing how/if this can be done for the sake of the exercise.
After trying a few new things, I'm returning to SO to get input. I'm stuck.
Here's what I have at this point…
public class EngMath
{
/// ---------------------------------------------------------------------------
/// Extend the Math Library to include EngVar objects.
/// ---------------------------------------------------------------------------
public static EngVar Abs(this Math m, EngVar A)
{
EngVar C = A.Clone();
C.CoreValue = Math.Abs(C.CoreValue);
return C;
}
public static EngVar Cos(this Math m, EngVar A)
{
EngVar C = A.Clone();
double Conversion = 1;
// just modify the value. Don't modify the exponents at all
// is A degrees? If so, convert to radians.
if (A.isDegrees) Conversion = 180 / Math.PI;
C.CoreValue = Math.Cos(A.CoreValue * Conversion);
// if A is degrees, convert BACK to degrees.
C.CoreValue *= Conversion;
return C;
}
...
Best Solution
Extension methods are a way to make your static methods appear to be instance methods on the type they "extend". In other words you need an instance of something in order to use the extension method feature.
It sound to me that you're going about it in the opposite way by trying to make Math.Cos handle your type. In that case, I'm afraid you have to implement the functionality yourself. If that is not what you're trying to do, please clarify.