dotnet / dotnet/vblang

Proposal: Interface constraint for generic parameters

Open
#419 0 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

### Motivation
I have implemented a helper function [CTypeWrap](https://github.com/Nukepayload2/Nukepayload2.Dynamic/blob/9881cb4d2b711c0a412cb321a76b4f0da0cc290b/Nukepayload2.Dynamic/DynamicConversion.vb#L17) to simulate structural typing of TypeScript with VB.NET . My teammates use this method to bring TypeScript codes to .NET.
It can convert an object to the specified interface without requiring the object implements that interface.

```vbnet
' Declaration
Function CTypeWrap(Of TSource, TInterface As Class)(source As TSource) As TInterface

' Usage
Class TestClass
Sub TestSub()
Console.WriteLine("Test")
End Sub
End Class

Interface ITest
Sub TestSub()
End Interface

' If the caller passes a type which is not an interface to the second generic parameter, the code still compiles.
' But it result in a runtime error.
Dim wrapped As ITest = CTypeWrap(Of TestClass, ITest)(testc)

' BTW, this code snippet should be runnable if ADG's top-level code feature is available
```
I need to make sure that the code won't compile with the latest compiler `If` `TypeOf` the second generic type parameter `IsNot` `Interface`.
Currently we use `Mono.Cecil` to check the compiled assembly with hard-coded constraints in our unit tests. We don't have enough time to write and test a custom analyzer.

### Suggested syntax
Allow interface generic constraint
```vbnet
Function CTypeWrap(Of TSource, TInterface As Interface)(source As TSource) As TInterface
```

#### Rules
1. The `Interface` constraint can't be unioned with one of the following constraints: `Class`, `Structure`, `New`, `Enum`, `Delegate` and user-defined non-interface types.
```vbnet
' This is allowed
Function CTypeWrap(Of TSource, TInterface As {Interface, IConvertible})(source As TSource) As TInterface
```
2. This constraint is optional. Old VB.NET compilers should treat the `Interface` constraint as `Class` for better backward compatibility.
```vbnet
' Old VB.NET compiler view
Imports System.Runtime.CompilerServices
' Don't use modopt or modreq.

Function CTypeWrap(Of TSource, TInterface As Class)(source As TSource) As TInterface
```
3. If this feature will be added to VB.NET, other .NET languages needs to support using the `Interface` constraint.

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.