Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override `is` operator

Tags:

c#

we know:

int? number = 10;
Console.WriteLine(number is int); // true

but:

NotNull<string> text = "10"; // NotNull<> is my struct
Console.WriteLine(text is string); // false

I want text is string return true, how can I do that?

-------------------------------- edit

here is my NotNull:

public class NotNull<T> where T : class
{
    public T Value { get; }

    private NotNull(T value)
    {
        this.Value = value;
    }

    public static implicit operator T(NotNull<T> source)
    {
        return source.Value;
    }

    public static implicit explicit NotNull<T>(T value)
    {
        if (value == null) throw new ArgumentNullException(nameof(value));
        return new NotNull<T>(value);
    }
}

if a class was declaring like:

public class A
{
    public NotNull<string> B { get; set; }
}

I just hope any serializer can serialize and deserialize it same as:

public class A
{
    public string B { get; set; }
}

-------------------------------- edit 2

I found this is a impossible question:

  1. if NotNull<> is class, default(NotNull<>) is null, I do nothing.
  2. if NotNull<> is struct, default(NotNull<>).Value is null.

sorry about the question.

like image 814
Cologler Avatar asked Oct 31 '15 20:10

Cologler


People also ask

Is operator overriding possible?

Operator Overloading in C++ In C++, we can make operators work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.

Can you override operators in C?

C does not support overloading of operators or functions. There's no way you can redefine < , <= , > , >= , == , or != to compare struct types directly.

Which function overloads the == operator?

In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .

Can we override operator in C++?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function.


1 Answers

On MSDN you have list of overloadable operators: Overloadable Operators (C# Programming Guide)

These operators cannot be overloaded:

=, ., ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is, new, sizeof, typeof

like image 102
Nejc Galof Avatar answered Oct 12 '22 12:10

Nejc Galof