Search code examples
c#classextending-classes

C# add to class in another DLL


...is it possible?

For example, can I add this simple function...

public static double Deg2Rad(double degrees) {
    return Math.PI / 180 * degrees;
}

...to the Convert class? So (using the default..."usings") you can call

double radians = Convert.Deg2Rad(123);

Can this be done? If so, how?


Solution

  • No you can't, but you can add an Extension method to double and call it like

    double x = 180.0;
    double y = Math.Cos( x.Deg2Rad() );
    double z = Math.Sin( 0.5.Pi() );
    

    in an static class add the following extension method:

    public static class ExtensionMethods
    {
        public static double Deg2Rad(this double angle)
        {
            return Math.PI*angle/180.0;
        }
    
        public static double Pi(this double x)
        {
            return Math.PI*x;
        }
    }