5

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
  • 4
    Is MyClass a struct? What argument does your constructor take? Commented Jan 6, 2010 at 1:36
  • Can you write it as an explicit operator instead? Commented Jan 6, 2010 at 1:38
  • I can't reproduce your issue; you probably have something else wrong. Commented Jan 6, 2010 at 1:39
  • 1
    d'oh, it makes sense. You cant have a null struct. Commented Jan 6, 2010 at 1:46

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
It's an implicit cast - the compiler would automatically insert the (MyClass)
Big thanks tho :) you got my answer while i provided incorrect details!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.