How to add methods to a native class?

5

How to add functions in a native C # class, in my case, I tried to do in System.Math just as test:

public class Math
{
    public static double test(double a)
    {
        return a;
    }
}

And call it like this:

Math.test(10);

But I did not get the expected result. How could I add the method in this class?

    
asked by anonymous 20.06.2017 / 00:27

2 answers

4

This is not possible today, and there is little advantage to doing this. Create a new and good class.

public class MathExt {
    public static double test(double a) => a;
}

MathExt.test(10);

In addition,     

20.06.2017 / 00:50
4

I believe that what you are looking for is called Extension Methods .

See more at: extension !

Using this concept, you can create extensions for all classes and structures, as long as they are not static.

The Math class is static and can not be extended:

Theotheranswersevenseemtowork,butinfactyouwouldbeaccessinganewclassandnottheexistingone:System.Math.

Seethedifferencebelow:

Listofmethodsofthenewclass,comparedtothelistofmethodsofclassSystem.Mathbelow:

Here'sanexampleofwhatadoubleextensionmightlookliketogetanidea:

classProgram{publicstaticvoidMain(){doubledez=10;Console.WriteLine("Dobro(10) => {0}", dez.Dobro());
        Console.WriteLine("Metade(10) => {0}", dez.Metade());             
    }    
}

public static class DoubleEx
{
    public static double Dobro(this double a)
    {
        return a * 2;
    }

    public static double Metade(this double a)
    {
        return a / 2;
    }
}

With the following output: Double (10) = > 20 Half (10) = > 5

    
20.06.2017 / 01:46