C# program to overload Less Than or Equal To (<=) and Greater Than or Equal To (>=) operators

Overload Less Than or Equal To (<=) and Greater Than or Equal To (>=) operators in C#: Here, we are writing a program to overload less than or equal to and greater than or equal to operators.
Submitted by IncludeHelp, on March 18, 2018

In C#, if we overload "Less Than or Equal To" (<=) operator then we must overload "Greater Than or Equal To" (>=) operators. Here, we will create a sample class with data member X. Assign value using Set() method.

Problem statement

Write a C# program to overload Less Than or Equal To (<=) and Greater Than or Equal To (>=) operators.

Program to overload <= and >= operators in C#

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Sample
    {
        private int X;
        
        public Sample()
        {
            X = 0;
        }

        public void Set(int v)
        {
            X = v;
        }
        public static bool operator<=(Sample S1, Sample S2)
        {
            return (S1.X <= S2.X);
        }

        public static bool operator>=(Sample S1, Sample S2)
        {
            return (S1.X >= S2.X);
        }
        
    }

    class Program
    {
        static void Main()
        {
            Sample S1 = new Sample();
            Sample S2 = new Sample();
           
            S1.Set(5);
            S2.Set(5);

            Console.WriteLine(""+(S1 <= S2));
            Console.WriteLine(""+(S1 >= S2));
        }
    }
}

Output

True
True

In this program, we took two object of sample class. And here we overloaded both "Less Than or Equal To" (<=) and "Greater Than or Equal To" (>=) operators. And both overloaded methods are returning Boolean value on the basis of "<=" and ">=" operators.

C# Operator Overloading Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.