dotnet / dotnet/vblang

Typed Dictionary

Open
#235 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
328
Forks
71
PR merge metrics
No merged PRs in 30d

Description

I hope VB.NET can add this new syntax:
```
Dictionary CityTemperaturesDic (Of String, Integer)
NewYork = 12
London = 10
Cairo = 15
End Dictionary
```

The compiler can use this to create a calss CityTemperaturesDic like this:

```
Public Class CityTemperaturesDic
Inherits Dictionary(Of String, Integer)

Public Sub New()
Me("NewYork") = 12
Me("London") = 10
Me("Cairo") = 15
End Sub

Public Property NewYork() As Integer
Get
Return Me("NewYork")
End Get
Set
Me("NewYork") = Value
End Set
End Property

Public Property London() As Integer
Get
Return Me("London")
End Get
Set
Me("London") = Value
End Set
End Property

Public Property Cairo() As Integer
Get
Return Me("Cairo")
End Get
Set
Me("Cairo") = Value
End Set
End Property
End Class

```
Now you can use this Typed Dictionary anywhere in you project or even expose it outside the project:
```
Dim Cities = new CityTemperaturesDic( )
Cities.NewYork = 6
If Cities.Cairo < 10 Then Console.WriteLine("Too Cold")
```

This will prevent misspelled key names, which lead to unexpected results. For example, if you use this code:
```
Cities["Cair"] = 5
If Cities["Cairo"] < 10 Then Console.WriteLine("Too Cold")
```

In design time, VB.NET can't detect the misspelled Key "Cair", and in runtime, the "Cair" key will be added to the Dictionary with value 5 without raising any exception, so the condition will always be false, because it deals with another key! This Can't happen in Typed dictionary, because a syntax error will happen in then line:
`Cities.Cair = 5`
And Intellisense with prevent that sort of mistakes.

Note:
we can make this part

```
Dictionary CityTemperaturesDic(Of String, Integer)
```

shorter, if we agreed that the keys will always be strings. I suggest:

`Dictionary CityTemperaturesDic (Of Integer)`

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.