On 22/06/2024 19:34, Robert Landers wrote:
I've brought this up before, but I mostly see "as" being useful for
static analysis. That's what I've mostly used it for C#, anyway.
Logically, you know the type, but due to one-thing-or-another you
can't "prove" the type is that type (such as foreach-arrays or dealing
with results from user-code callbacks in library code). I want to be
able to say "this is an int or else."


I absolutely see the use case for that; I just don't think "as" is a good word for it, because that's not what it means in normal English.


Incidentally, according to the C# docs at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#as-operator

> The as operator explicitly converts the result of an expression to a given reference or nullable value type. If the conversion isn't possible, the as operator returns null. Unlike a cast expression, the as operator never throws an exception.

So it more closely matches my intuition: a statement of just "foo as Bar;" would be useless, because it's calculating a value and discarding it, with no side effects.

As you say, the conversion might not be of the value, but of the statically analysed type, but in C#, that's all part of the language. In PHP "$foo = $bar as SomeInterface;" would have no visible effect except in third-party tooling, where it can already be written "/** @var SomeInterface $foo */ $foo = $bar;"


--
Rowan Tommins
[IMSoP]

Reply via email to