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
This cannot be done, because member look-up operator .
does not take members of types other than that of ForeignKey
into consideration.
Section 7.4 explains the process.
A member lookup of a name N with K type parameters in a type T is processed as follows:
- First, a set of accessible members named N is determined
- Next, if K is zero, all nested types whose declarations include type parameters are removed. If K is not zero, all members with a different number of type parameters are removed.
- Next, if the member is invoked, all non-invocable members are removed from the set.
- Next, members that are hidden by other members are removed from the set.
- Next, interface members that are hidden by class members are removed from the set. This step only has an effect if T is a type parameter and T has both an effective base class other than object and a non-empty effective interface set.
- Finally, having removed hidden members, the result of the lookup is determined:
- If the set consists of a single member that is not a method, then this member is the result of the lookup.
- Otherwise, if the set contains only methods, then this group of methods is the result of the lookup.
- Otherwise, the lookup is ambiguous, and a binding-time error occurs.
Since C# does not consider conversion operators in the process of member resolution, your only option is to add the method to your class, either directly or through an extension.