Search code examples
c#classstructnullablebehavior

Creating C# Class or Struct with behavior like Nullable


I'm trying to create a simple class or struct that behave like Nullable struct

Sample Code:

// This Class Behave like Nullable<int>
public class SomeClass
{
    public SomeClass()
    {
    }

    public void ProcessValue()
    {
        ... Body ...
    }

    public bool HasValue
    {
        get { return true; }
    }
}

public static class Main
{
    static void Main()
    {
        SomeClass a = 20; //int Type
        a.ProcessValue();
    }
}

Can this is even posible? I'm try to search everywhere, but got no luck finding the answer. Or maybe I don't know what the search keywords is.

Can Somebody help me.

Thanks A'an


Solution

  • You could implement the implicit cast operator to assign an integer to your type. But that seems to be a bad design. I would not recommend to do so.