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?
var x = myClass; // And here is important that x is of type int!
I don't think this will ever fly. – Hostageimplicit operator int
? – Segalvar x = myClass
causingx
to be of typeint
is a non-starter. – Fixatevar x = myClass
. TBH, it doesn't really make much sense to me to try to do this... Thinking about use cases, it is implicitly convertible to int, so can be used (in most places) instead of an int. OP, why do you want this to be so? – Hostagepublic static implicit operator int(MyClass instance) { return instance.Value; }
soMyClass myClass = 1;
is valid – Oberhausenpublic static implicit operator int(MyClass b)
, butx
will still be of typeMyClass
. – Spermatozoonint
value (kind of enum, but with custom methods) and it works: I can assign int and I can use instance of class as int in expressions. I am not quite sure what you mean. Another question is what doesn't work for OP,implicit operator
is the way to go. – Segalvar x = myClass
, x will never be anything other than the type ofmyClass
. – LimeGetSomething<T>
and store some other information in this class, but if I want to 'work' with this class, it should be as if I'm working with an int. – Oberhausen((MyClass)someInt).SomeMethod()
orMyClass someVar = someInt; someVar.SomeMethod();
– Segalint
occurs. The approach is only good if both types can be converted to each other without any loss. Or if you don't mind what other properties will have default value. – Segal