Call Function with Implicit Type Conversion

Viewed 606

I have a class like this.

public class ForeignKey {
    public string Id {get;}
    public TableA TableA {get;}
    public TableB TableB {get;}
    public static implicit operator string(ForeignKey obj){ return obj.Id; }
    public override string ToString() { return Id; }
    /* various operator overloads */
}

I would like to have automatic type conversion on it so I can it use like a string. What I've done so far lets me use it in a number of places without an explicit cast. However, I can't figure out a way to call string functions without doing an explicit cast.

For example, I'd like to get this to work.

if (Key.EndsWith(someValue))

Currently I have to do this

if (((string)Key).EndsWith(someValue))
// or
if (Key.Id.EndsWith(someValue))

Is there a way to get it to work how I want?

Thanks

2 Answers
Related