VB.NET Syntax and String Extension Methods

Code in VB.NET

Module Utils <Runtime.CompilerServices.Extension()> _ Public Sub Print(ByVal message As String) Console.WriteLine(message) End Sub End Module Public Class Foo Public Sub New() Dim test = "cucu" test.Print() ' no problem: custom string extension method ' "cucu".Print() ' syntax error ' End Sub End Class 

1) The first problem, I would prefer to use "cucu" .MyExtensionMethod (), as well as test.MyExtensionMethod ();

1 ') Syntax like

  "No Result".Print() ' Print is an extension method ' " No Result ".Trim() ' Trim is a framework method ' 

both of them do not work

However, the syntax is kind of

  myTextBox.Text = "No Result".Translate() ' Translate is an extension method ' myTextBox.Text = " No Result ".Trim() ' Trim is a framework method ' 

works very well.

So, there seems to be some consistency in the string behavior sequence.

2) Look at the COMMENTS (in the attached figure). The words "custom", "string" and "error" are highlighted, however they are in the comments, so they should be green, not blue.

Why is this? What is the workaround?

EDIT:

Declared as β€œerror” in Microsoft Connect (even if it is no more syntactic β€œmiss”) ...

EDIT 2:

As Hans Passant noted, standard string methods like "cucu".Trim() do not work either.

+7
source share
2 answers

I can confirm that this is really a β€œbug” (tested in Visual Studio 2008). But in fact, its design in VB will not be changed.

However, I'd like to take the time to explain why this is a terrible question. Sorry Sergio.

  • It does not list all the steps necessary to reproduce the problem.
  • It does not provide complete code.
  • This does not reduce the problem to the minimum (do not use Infer here - this distracts from the problem)
  • As a result, there are a hundred different reasons that would fully explain this behavior without error (for example, see stakx excellent (now deleted) answer).

Here is a complete example using the default settings for VB that do not have these problems (create a new empty solution for the console project and paste this code into Module1.vb ):

 Module Extensions <System.Runtime.CompilerServices.Extension()> _ Public Sub ShowDialog(ByVal message As String) Console.WriteLine(message) End Sub End Module Module Module1 Sub Main() Dim s As String = "Hello" s.ShowDialog() ' Doesn't work: '"World".ShowDialog() ' Works: Call "World".ShowDialog() End Sub End Module 

The behavior is consistent in VB: you cannot have a value as the first token in a logical line. For example, the following code also does not compile (taking into account the existing, corresponding definition of the form class Form1 ):

 New Form1().ShowDialog() 

and again the fix should prefix the Call expression:

 Call New Form1().ShowDialog() 
+8
source

You can do CStr("cucu").ShowDialog()

+2
source

All Articles