views:

130

answers:

1

I have this function

public static implicit operator MyClass(string v) { return new MyClass(v); }

and write var.myclass = null;. This calls the implicit operator and passes null as string, which causes havoc in my code (i use reflection and would not like to add a special case). How can i write myclass = null without causing the implicit operator?

I tried writing

public static implicit operator MyClass(string v) { return  v == null ? null : new MyClass(v); }

But that causes a stackoverflow

+4  A: 

I believe that your problem is that both sides of the ternary operator must be of the same or compatible types.

Try writing

if (v == null)
    return null;
else
    return new MyClass(v);

EDIT: I can only reproduce your issue if I make MyClass a struct, in which case your question is impossible; a struct cannot be null.

Please provide more details.

SLaks
You're thinking of a compile time error, which would be fixed by changing it to:return v == null ? (MyClass)null : new MyClass(v);The stack overflow is likely going to be a runtime error, where it calls the implicit operator recursively.
Merlyn Morgan-Graham
It's an implicit cast - the compiler would automatically insert the `(MyClass)`
SLaks
It was a struct. oops.
acidzombie24
Big thanks tho :) you got my answer while i provided incorrect details!
acidzombie24