2

I have a variable theetaCurrent which is being sent by another application to me in 10th of a degree. I can very easily convert it everywhere by using a function but i want to do something like theetaCurrent.ToRadians(). First of all, is it possible? if yes, then how? Below is my current method

double inRadians (double angleIn10thofaDegree)
{
    // Angle in 10th of a degree
    return (angleIn10thofaDegree*Math.PI)/1800; 
}

Thanks for your help.

Abhishek Kumar
  • 342
  • 5
  • 22

1 Answers1

7

Yes, you can define an extension method:

public static class Foo {

    public static double ToRadians (this double angleIn10thofaDegree) {
        // Angle in 10th of a degree
        return (angleIn10thofaDegree * Math.PI)/1800; 
    }

}

In boldface the changes you have to make:

  • make the method static;
  • change the name to ToRadians;
  • add this to the parameter; and
  • define the method in a static class.

You only have to change the name if you want to call it with theetaCurrent.ToRadians() of course.

In order to use the extension method, you have to use the namespace in which Foo is defined.

You can the call it with:

double result = original.ToRadians();

If you however aim to perform in-place transformations using an extension method, for example something like:

double theetaCurrent = 180/Math.PI;
theetaCurrent.ToRadians();
//now theetaCurrent is 0.1

That would be an extension method with call-by-reference which is - as far as I know - not supported. See a StackOverflow answer of Jon Skeet here.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555