Home » C# programs

C# program to overload binary operator '*'

In this article, we will learn about how to overload a binary multiply ‘*’ operator in C#? It’s an example of overload binary operator ‘*’ asterisk in C#.Net.
Submitted by IncludeHelp, on March 15, 2018

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

Program to overload binary '*' operator 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 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(30);
            S2.Set(20);

            S3 = S1 * S2;

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

Output

Value : 30
Value : 20
Value : 600

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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




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.