Home » C# programs

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




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.