C# - Can we overload left shift (<<) to perform Left shift operation?

In this C# program, we are going to learn can we overload a left shift operator (<<) to perform left shift operation? Here is an example, that will tell you how can we overload it in C#?
Submitted by IncludeHelp, on March 18, 2018

In C#, we can perform left shift operation between two objects, but we can do it by passing a integer argument in 'operator' method.

Example:

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 int operator <<(Sample S1, int num)
        {
            int temp = 0;

            temp = S1.X << num;
           
            return temp;
        }

        
    }

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

            int num = 0;

            S1.Set(3);

            num = S1 << 2;

            Console.WriteLine("NUM : " + num);
            
        }
    }
}

Output

NUM : 12

C# Operator Overloading Programs »


Comments and Discussions!

Load comments ↻






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