Question

I am using my own LargeWholeNumber class for integer values. In System.Math class there are a number of Max methods for applicable types. Am I able to create an overload for this Max method which compares LargeWholeNumber instances also?

I tried creating my own Math class which inherits from System.Math, but it says "Cannot inherit from sealed class 'Math'".

Thanks in advance for your advices.

Was it helpful?

Solution 2

No, basically. For instance methods, you can use extension methods to add new pseudo-overloads. This is not possible for static methods.

OTHER TIPS

You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.

reference from here: http://msdn.microsoft.com/en-us/library/ebca9ah3.aspx

So if the System method is virtual, you can override it. If no, you can't.

If you want to override a System method is non-virtual, I recommend you use extension method

You can't inherit a sealed class. The best solution for your problem would be to write your own Math class or use extension methods.

    void Main()
    {
        var a = new LargeWholeNumber{Number = 2};
        var b = new LargeWholeNumber{Number = 3};

        var bigger = a.Max(b);
        var bigger2 = ExtMethods.Max(a,b);
    }


    public class LargeWholeNumber 
    {
        public int Number {get;set;}
    }


    public static class ExtMethods
    {
        public static LargeWholeNumber Max(this LargeWholeNumber inNumber, 
LargeWholeNumber secondNumber)
        {
            if(inNumber.Number >= secondNumber.Number)
                return inNumber;
            else 
                return secondNumber;
        }

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top