C# program to overload binary modulus operator '%'

In this C# program, we are going to learn how to overload binary modulus operator (%)? Here is an example of overload binary modulus (%) operator in C#.
Submitted by IncludeHelp, on March 15, 2018

Problem statement

Write a C# program to overload binary modulus operator '%'.

Program to overload binary modulus '%' operator in C#

Here we will create a sample class with data member X. Assign value using Set() method and print data member value using printValue() method.

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 Sample operator %(Sample S1, Sample S2)
        {
            Sample temp = new Sample();

            temp.X = S1.X % S2.X;
           
            return temp;
        }

        public void printValue()
        {
            Console.WriteLine("Value : {0}", X);
        }
    }

    class Program
    {
        static void Main()
        {
            Sample S1 = new Sample();            
            Sample S2 = new Sample();
            Sample S3 = new Sample();

            S1.Set(40);
            S2.Set(15);

            S3 = S1 % S2;

            S1.printValue();
            S2.printValue();
            S3.printValue();
        }
    }
}

Output

Value : 40
Value : 15
Value : 10

In this program we created two object of class sample S1, S2 and S3. Then divide value of S1 from S2 and then remainder assigned to S3.

C# Operator Overloading Programs »

Comments and Discussions!

Load comments ↻





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