Skip to content

Commit 67c9a40

Browse files
CopilotBillWagnergewarren
authored
Add comprehensive examples to BC42328.md to improve understanding (#48310)
* Initial plan * Add comprehensive examples to BC42328.md to improve clarity Co-authored-by: BillWagner <[email protected]> * Apply suggestions from code review * Apply suggestions from code review Co-authored-by: Genevieve Warren <[email protected]> * Apply suggestions from code review Co-authored-by: Genevieve Warren <[email protected]> * Move large inline code example to snippet file and use proper reference Co-authored-by: BillWagner <[email protected]> * Replace inline code with snippet reference to eliminate duplication Co-authored-by: BillWagner <[email protected]> * Remove redundant "Complete working example" section as requested Co-authored-by: BillWagner <[email protected]> --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: BillWagner <[email protected]> Co-authored-by: Bill Wagner <[email protected]> Co-authored-by: Genevieve Warren <[email protected]>
1 parent ca904bf commit 67c9a40

File tree

3 files changed

+176
-41
lines changed

3 files changed

+176
-41
lines changed

docs/visual-basic/misc/bc42328.md

Lines changed: 83 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -24,28 +24,15 @@ Visual Basic allows you to assign methods to delegates even when their signature
2424

2525
## When this warning occurs
2626

27-
This warning appears when Visual Basic can handle the assignment through relaxed conversion, making the explicit `AddressOf` unnecessary. For example:
27+
This warning appears when Visual Basic can handle the assignment through relaxed conversion, making the explicit `AddressOf` unnecessary.
2828

29-
```vb
30-
' Event delegate expects (sender As Object, e As EventArgs)
31-
Public Event SomeEvent As EventHandler
29+
### Complete example showing the warning
3230

33-
' Method with exact signature - no warning
34-
Sub Handler1(sender As Object, e As EventArgs)
35-
' Implementation
36-
End Sub
31+
The following example shows one scenario that produces BC42328:
3732

38-
' Method with omitted parameters - causes BC42328
39-
Sub Handler2()
40-
' Implementation
41-
End Sub
33+
:::code language="vb" source="snippets/bc42328/AddressOfExample.vb" id="DocumentProcessor":::
4234

43-
' Using AddHandler with exact match - no warning
44-
AddHandler SomeEvent, AddressOf Handler1
45-
46-
' Using AddHandler with relaxed conversion - causes BC42328
47-
AddHandler SomeEvent, AddressOf Handler2
48-
```
35+
When you compile this code, Visual Basic shows the BC42328 warning for the `AddHandler` statements that use relaxed delegate conversion.
4936

5037
## Why AddressOf appears to have "no effect"
5138

@@ -57,36 +44,72 @@ However, `AddressOf` is still syntactically required in `AddHandler` and `Remove
5744

5845
## To correct this error
5946

60-
You have several options depending on your needs:
47+
You have several options depending on your needs. Using the `DocumentProcessor` example from previously, here are the different ways to resolve the BC42328 warning:
6148

62-
- **Assign to a variable first (preserves exact semantics):**
49+
### Option 1: Assign to a variable first (preserves exact semantics)
6350

64-
```vb
65-
Dim handler As EventHandler = AddressOf Handler2
66-
AddHandler SomeEvent, handler
67-
```
51+
```vb
52+
Public Sub DemonstrateHandler()
53+
' Create delegate variable first - this eliminates the warning
54+
Dim handler As EventHandler = AddressOf OnDocumentProcessed_Simple
55+
AddHandler DocumentProcessed, handler
56+
End Sub
57+
```
6858

69-
- **Match the delegate signature exactly:**
59+
### Option 2: Match the delegate signature exactly
7060

71-
```vb
72-
Sub Handler2(sender As Object, e As EventArgs)
73-
' Implementation - use parameters or ignore them
74-
End Sub
75-
```
61+
```vb
62+
' Change the method signature to match EventHandler exactly
63+
Private Sub OnDocumentProcessed_Simple(sender As Object, e As EventArgs)
64+
' You can ignore the parameters if you don't need them
65+
Console.WriteLine("Document processed (simple)")
66+
End Sub
7667

77-
- **Use a lambda expression:**
68+
Public Sub DemonstrateHandler()
69+
' Now this works without warning
70+
AddHandler DocumentProcessed, AddressOf OnDocumentProcessed_Simple
71+
End Sub
72+
```
7873

79-
```vb
80-
AddHandler SomeEvent, Sub() Handler2()
81-
```
74+
### Option 3: Use a lambda expression
8275

83-
- **Use the `Handles` clause if appropriate:**
76+
```vb
77+
Public Sub DemonstrateHandler()
78+
' Wrap the method call in a lambda that matches the signature
79+
AddHandler DocumentProcessed, Sub(sender, e) OnDocumentProcessed_Simple()
80+
81+
' Or create a more complex lambda inline
82+
AddHandler DocumentProcessed,
83+
Sub(sender, e)
84+
Console.WriteLine($"Event from {sender}")
85+
OnDocumentProcessed_Simple()
86+
End Sub
87+
End Sub
88+
```
89+
90+
### Option 4: Use the `Handles` clause (if appropriate)
8491

85-
```vb
86-
Sub Handler2() Handles someObject.SomeEvent
87-
' Implementation
88-
End Sub
89-
```
92+
```vb
93+
Public Class DocumentHandler
94+
' Declare the event source with WithEvents
95+
Private WithEvents processor As DocumentProcessor
96+
97+
' Use Handles clause - no AddHandler needed
98+
Private Sub OnDocumentComplete() Handles processor.DocumentProcessed
99+
Console.WriteLine("Document processing is done!")
100+
End Sub
101+
End Class
102+
```
103+
104+
### Option 5: Direct assignment to delegate variable
105+
106+
```vb
107+
Public Sub DemonstrateHandler()
108+
' Assign to delegate variable then use with AddHandler
109+
Dim handler As EventHandler = AddressOf OnDocumentProcessed_Simple
110+
AddHandler DocumentProcessed, handler
111+
End Sub
112+
```
90113

91114
## When you can ignore this warning
92115

@@ -95,8 +118,27 @@ This warning is often safe to ignore when:
95118
- Your handler method intentionally omits parameters it doesn't need.
96119
- You're using a simpler method signature for cleaner code.
97120
- The performance impact is negligible for your application.
121+
- You're prototyping or writing quick utility code where clarity matters more than efficiency.
122+
123+
The relaxed conversion works correctly; this warning just indicates a minor efficiency consideration. The compiler creates a wrapper delegate automatically, which adds a small performance overhead but doesn't affect functionality.
98124

99-
The relaxed conversion works correctly; this warning just indicates a minor efficiency consideration.
125+
### Example of when ignoring is appropriate
126+
127+
```vb
128+
Public Class QuickLogger
129+
Public Event LogMessage As Action(Of String, DateTime)
130+
131+
' Simple handler that ignores the timestamp parameter
132+
Private Sub WriteToConsole()
133+
Console.WriteLine("Something was logged")
134+
End Sub
135+
136+
Public Sub SetupLogging()
137+
' This generates BC42328, but it's fine for simple scenarios
138+
AddHandler LogMessage, AddressOf WriteToConsole
139+
End Sub
140+
End Class
141+
```
100142

101143
## See also
102144

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
Imports System
2+
3+
' <DocumentProcessor>
4+
Public Class DocumentProcessor
5+
' Standard .NET event using EventHandler
6+
Public Event DocumentProcessed As EventHandler
7+
8+
' Custom event with different signature
9+
Public Event StatusChanged As Action(Of String)
10+
11+
' Handlers with different signatures
12+
13+
' Exact match for EventHandler - no warning
14+
Private Sub OnDocumentProcessed_Exact(sender As Object, e As EventArgs)
15+
Console.WriteLine("Document processed (exact signature)")
16+
End Sub
17+
18+
' Simplified handler - causes BC42328 with EventHandler
19+
Private Sub OnDocumentProcessed_Simple()
20+
Console.WriteLine("Document processed (simple)")
21+
End Sub
22+
23+
' Handler for custom event - exact match
24+
Private Sub OnStatusChanged_Exact(message As String)
25+
Console.WriteLine($"Status: {message}")
26+
End Sub
27+
28+
' Handler with ignored parameters - causes BC42328 with custom event
29+
Private Sub OnStatusChanged_Simple()
30+
Console.WriteLine("Status changed")
31+
End Sub
32+
33+
Public Sub DemonstrateWarnings()
34+
Console.WriteLine("Setting up event handlers...")
35+
36+
' These work without warnings (exact matches)
37+
AddHandler DocumentProcessed, AddressOf OnDocumentProcessed_Exact
38+
AddHandler StatusChanged, AddressOf OnStatusChanged_Exact
39+
40+
' These generate BC42328 warnings (relaxed conversions)
41+
AddHandler DocumentProcessed, AddressOf OnDocumentProcessed_Simple
42+
AddHandler StatusChanged, AddressOf OnStatusChanged_Simple
43+
44+
' Fire the events
45+
RaiseEvent DocumentProcessed(Me, EventArgs.Empty)
46+
RaiseEvent StatusChanged("Processing complete")
47+
End Sub
48+
49+
Public Sub DemonstrateSolutions()
50+
Console.WriteLine("Using solutions to avoid warnings...")
51+
52+
' Solution 1: Assign to variable first
53+
Dim handler1 As EventHandler = AddressOf OnDocumentProcessed_Simple
54+
AddHandler DocumentProcessed, handler1
55+
56+
' Solution 2: Use lambda expression
57+
AddHandler DocumentProcessed, Sub(s, e) OnDocumentProcessed_Simple()
58+
59+
' Solution 3: Direct assignment to delegate variable
60+
Dim handler2 As Action(Of String) = AddressOf OnStatusChanged_Simple
61+
AddHandler StatusChanged, handler2
62+
63+
' Fire the events
64+
RaiseEvent DocumentProcessed(Me, EventArgs.Empty)
65+
RaiseEvent StatusChanged("All solutions work")
66+
End Sub
67+
End Class
68+
' </DocumentProcessor>
69+
70+
Module Program
71+
Sub Main()
72+
Dim processor As New DocumentProcessor()
73+
74+
Console.WriteLine("=== Demonstrating BC42328 Warning ===")
75+
processor.DemonstrateWarnings()
76+
77+
Console.WriteLine()
78+
Console.WriteLine("=== Demonstrating Solutions ===")
79+
processor.DemonstrateSolutions()
80+
81+
Console.WriteLine("Press any key to exit...")
82+
Console.ReadKey()
83+
End Sub
84+
End Module
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net8.0</TargetFramework>
6+
<RootNamespace>BC42328Example</RootNamespace>
7+
</PropertyGroup>
8+
9+
</Project>

0 commit comments

Comments
 (0)