C# program to overload Logical NOT (!) operator

Overload Logical NOT (!) Operator in C#: Here, we are writing a program to overload Logical NOT (!) Operator, which is a Unary Operator.
Submitted by IncludeHelp, on March 18, 2018

Problem statement

To demonstrate an Example of Overloading Logical NOT (!) Operator in C#, here we are creating a sample class with data member X. Assign value using Set() method.

Program to overload Logical NOT (!) in C#

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Sample
    {
        private bool X;
        
        public Sample()
        {
            X = false;
        }

        public void Set(bool v)
        {
            X = v;
        }
        public static bool operator!(Sample S)
        {
            return !(S.X);
        }
        
    }

    class Program
    {
        static void Main()
        {
            Sample S1 = new Sample();
            Sample S2 = new Sample();
           
            S1.Set(true);
            S2.Set(false);

            Console.WriteLine(""+!S1);
            Console.WriteLine(""+!S2);
        }
    }
}

Output

False
True

In this program, we took two object of sample class. And here we overloaded "Logical AND (!) operator. And both overloaded methods are returning Boolean values on the basis of values set by Set() method.

C# Operator Overloading Programs »

Comments and Discussions!

Load comments ↻





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