Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion without assignment?

Preserved question - see Edit at the bottom
I'm working on a small functional library, basically to provide some readability by hiding basic cyclomatic complexities. The provider is called Select<T> (with a helper factory called Select), and usage is similar to

public Guid? GetPropertyId(...)
{
    return Select
        .Either(TryToGetTheId(...))
        .Or(TrySomethingElseToGetTheId(...))
        .Or(IGuessWeCanTryThisTooIfWeReallyHaveTo(...))
        //etc.
        ;
}

and the library will take care of the short circuiting, etc. I also added an implicit conversion from Select<T> to T, so I can write

public Guid GetPropertyId(...)
{
    ServiceResult result = Select
        .Either(TryToGetTheId(...))
        .Or(TrySomethingElseToGetTheId(...));

    return result.Id;
}

What I'd really like to be able to do is an implicit conversion to T without assignment:

public Guid GetPropertyId(...)
{
    return 
        //This is the part that I want to be implicitly cast to a ServiceResult
        Select
        .Either(TryToGetTheId(...))
        .Or(TrySomethingElseToGetTheId(...))
        //Then I want to access this property on the result of the cast
        .Id;
}

However, the specified syntax doesn't work - I have to either assign it to a variable, or explicitly cast it. Is there a way to get an implicit cast inline?

EDIT

What I want to do is this:

class Foo { 
    public int Fuh { get; set; } 
}

class Bar {
    private Foo _foo;
    public static implicit operator Foo (Bar bar)
    {
        return bar._foo;
    }
}

//What I have to do
Foo bar = GetABar();
DoSomethingWith(bar.Fuh);

//What I want to do
DoSomethingWith(GetABar().Fuh);
like image 613
Matt Mills Avatar asked Dec 10 '22 14:12

Matt Mills


1 Answers

While it's true that an implicit cast won't work here, you could possibly do better than an explicit cast by adding a Value property to Select<T>. Then your expression would be Select.[operations].Value.Id, which still reads reasonably well.

like image 119
zinglon Avatar answered Dec 14 '22 22:12

zinglon