Search code examples
c#operatorsvariable-assignmentassignment-operatorvalue-type

C# Class as one Value in Class // Mimic int behaviour


Is there a way to make my new Class mimic the behavior of an int or any Valuetype?

I want something, so these assignments are valid

MyClass myClass = 1;
int i = myClass;
var x = myClass; // And here is important that x is of type int!

The MyClass looks roughly like this

public class MyClass {
    public int Value{get;set;}
    public int AnotherValue{get;set;}
    public T GetSomething<T>() {..}
}

Every assignment of MyClass should return the Variable Value as Type int.

So far i found implicit operator int and implicit operator MyClass (int value). But this is not 'good enough'.

I want that MyClass realy behaves like an int. So var i = myClass lets i be an int.

Is this even possible?


Solution

  • If you´d created a cast from your class to int as this:

    public static implicit operator int(MyClass instance) { return instance.Value; }
    

    you could implicetly cast an instance of MyClass to an int:

    int i = myClass;
    

    However you can not expect the var-keyword to guess that you actually mean typeof int instead of MyClass, so this does not work:

    var x = myClass;  // x will never be of type int
    

    Apart from this I would highly discourage from an implicit cast as both types don´t have anything in common. Make it explicit instead:

    int i = (int) myClass;
    

    See this excellent answer from Marc Gravell for why using an explicit cast over an implicit one. Basically it´s about determing if data will be lost when converting the one in the other. In your case you´re losing any information about AnotherValue, as the result is just a primitive int. When using an explicit cast on the other hand you claim: the types can be converted, however we may lose information of the original object and won´t care for that.