ValueOf icon indicating copy to clipboard operation
ValueOf copied to clipboard

IValueOf with static abstract From(TValue) at the cost of compatibility

Open BreadTh opened this issue 4 years ago • 2 comments

Perhaps a change for later when there's greater compatibility, but having the static From function in an interface is amazing! (and just what I needed)

BreadTh avatar Sep 17 '21 09:09 BreadTh

What's an example of usage?

mcintyre321 avatar Sep 17 '21 10:09 mcintyre321

Allowing a class (StringExpectation) that is derrived from ValueOf to call the static .From on a class (GreetingMessage) that in turn derrives from itself. ValueOf => StringExpectation => GreetingMessage

Simplified example:

public class StringExpectation<TSelf> : ValueOf<string, TSelf> where TSelf : StringExpectation<TSelf>, IValueOf<string, TSelf>
{
    public static TSelf From(JToken token) =>
        //Do a bunch of validation with the token, and finally:
        TSelf.From(token.ToString());
}

public class GreetingMessage : StringExpectation<GreetingMessage> { }

The compiler does not understand that TSelf.From(string) exists alone from TSelf : StringExpectation<TSelf>, or even from TSelf : ValueOf<string, TSelf>

Implementing IValueOf<TValue, TThis> with static abstract From(TValue) allows such behaviour.

BreadTh avatar Sep 17 '21 10:09 BreadTh