Home » C# programs

C# program to overload less than (<) and greater than (>) operators

Overload less than (<) and greater than (>) operators in C#: Here, we are writing a program to overload less than and greater than relational operators.
Submitted by IncludeHelp, on March 18, 2018

In C#, if we overload "less than" (<) operator then we must overload "greater than" (>) operators. Here, we will create a sample class with data member X. Assign value using Set() method.

Program to overload less than (<) and greater than (>) 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(3);

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

Output

False
True

In this program, we took two object of sample class. And here we overloaded both "less than" (<) and "greater than" (>) operators. And both overloaded methods are returning Boolean value on the basis of "<" and ">" operators.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.