dotnet / dotnet/vblang

Proposal: Variabes, parameters and properties with range validation

Open
#464 17 comments 1 reaction 0 assignees View on GitHub
Dominant language
No language data
Stars
328
Forks
71
PR merge metrics
No merged PRs in 30d

Description

This is a feature I am waiting for for years, even before ASP.NET MVC added some validation attributes to the Model members, and I am wondering why this didn't happen until now!

We can force variables to accept some values only like this:
```VB.NET
Dim x As Integer In [20, 40] ' From 10 to 10
Dim y As Integer In {1, 3, 7, 10} ' Discrete values
Dim z As Integer In [20, 40] Or {1, 3, 7, 10}
x = 3 ' OK
y = 100 ' Exception
z = 5 ' Exception
```

This can be lowered to:
```VB.NET
Dim x As Integer
Dim y As Integer
x = Assign_x(3)
y = Assign_y(100)
z = Assign_z(5)
```

Where:
```VB.NET
private Function Assign_x(value as integer) As integer
If value < 20 OrElse value > 40 Then Throw New OverflowException()
Return Value
End Sub

private sub Function Assign_y(value As integer) As integer
If Not {1, 3, 7, 10}.Contains(value) Then Throw New OverflowException()
Return Value
End Sub

private Function Assign_z(value As integer) As integer
If value < 20 OrElse value > 40 Then Throw New OverflowException()

If Not {1, 3, 7, 10}.Contains(value) Then Throw New OverflowException()
Return Value
End Sub
```

Note: If the x is set via a ByRef parameter, then the Assign_x should be called when setting that parameter inside the function.

The real benefit of this is to have an easy way to force some constrains over property values and function params:
```VB.NET
Function Foo(x As Integer In[1, 10])

End Function

Property Prop1 As String In {"Red", "Green", "Blue"}
```

In this case, VB can add the validation conditions for the param or the value in the beginning of the function or the Set block. The back field of the property should be validated also.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.