Type Narrowing¶
Sharpy performs type narrowing in conditional branches:
value: str? = get_optional_string()
if value is not None:
# Inside this block, 'value' is narrowed from 'str?' to 'str'
print(value.upper()) # OK - value is str, not str?
else:
print("No value provided")
# isinstance() narrowing
obj: object = get_value()
if isinstance(obj, str):
# obj is narrowed to str
print(obj.upper())
Type narrowing does not occur with or as type union semantics do not exist in Sharpy:
Narrowing Rules¶
is not Nonenarrows nullable type (T?) to non-nullable (T)is Nonenarrows to never-type in theifbranchisinstance(x, Type)narrowsxtoTypein theifbranch- Narrowing only affects the scope of the conditional block
Implementation - ✅ Native - C# supports flow analysis for nullable types.