Syntax – can be a class method called at New without a helper variable? - vb.net

Having sample trivial class
Class A
Property Property1 As Integer = 5
Sub Action1()
Debug.Print(Property1.ToString())
End Sub
End Class
I can always call Action1() like
Dim instanceA As New A
instanceA.Action1()
But can I call the method without using the variable? Something like
(New A).Action1()
I'm getting syntax error at the 1st character when attempting that.

The reason that you get a syntax error is that a line of VB code cannot begin with the New keyword. I find that the best way around that is to use the otherwise useless Call keyword:
Call New A().Action1()

Related

How do I write a VB class which allows indexing into/calling an instance?

I'm honestly not sure what this is called, and if I did I'm sure I could google it in about 5 seconds.
I want to be able to write a class that I can sort of "index into" the way you do with a collection, eg:
Public Class FooClass
Public Function magicKeyword(param as String) as String
If param = "foo" Then
Return "bar"
Else
Return "baz"
End If
End Function
...
End Class
And then use it like this:
Dim myObj as New FooClass
Dim output as String = myObj("foo") '<-- this is what I want to know how to do
' output = "bar"
What is this called, and what syntax would I use for the function?
Out of curiosity, can this also be done as a Shared function so the class itself can do it? e.g.:
Dim output as String = FooClass("foo")
What you are describing is implementing a custom collection, and Microsoft provides a pretty good guide on how to accomplish this.
It should be said, however, that the collection classes already provided in .NET should be able to handle most use cases. A truly custom collection is overkill in many instances.

cast list to another type and change variable of each element of it

I have the next class: SearchResultWithDetails.
It inherits from SearchResult that implements ISearchResult.
In addition, I have a list of ISearchResult that is called result.
I want to cast the result into SearchResultWithDetails and set ShortDescription to be the same value as DetailsText.
ShortDescription and DetailsText are variables of the result.
I tried something like:
results.Cast(Of SearchResultWithDetails).ForEach(Function(item)
item.ShortDescription = item.DetailsText)
But it doesn't change the variable of ShortDescription to be the same as DetailsText.
Any help appreciated!
With option strict On you'll see that the ToList method is not an extension method, it's actually part of the List<T> class. This method accepts an Action<T> aka. sub, not a Func<T> aka. function. Apply all these fixes and the code should look like this:
Single-line:
results.OfType(Of SearchResultWithDetails).ToList().ForEach(Sub(item) item.ShortDescription = item.DetailsText)
Multiline:
results.OfType(Of SearchResultWithDetails).ToList().ForEach(
Sub(item)
item.ShortDescription = item.DetailsText
End Sub)

String.Substring(start, end) sometimes throwing an exception

My program uses a BackgroundWorker to call a PerformAction() method when a different method, Method1 returns true. I also am using the Strategy Pattern to set the correct PerformAction() that should be performed every time the event is raised.
For the Strategy Pattern I created an Abstract Class, and then a class inside the abstract class that inherits it.
Public MustInherit Class Abstract
Public MustOverride Sub PerformAction(ByVal str as String)
Public Class Extends
Inherits Abstract
Public Overrides Sub PerformAction(ByVal str as String)
str = str.Substring(str.IndexOf(":"), str.IndexOf(">"))
MsgBox(str)
End Sub
End Class
I create another class that contains a field of Abstract, and that is used to call PerformAction.
The PerformAction method gets called from the BackgroundWorker.ReportProgress event, which is called when BackgroundWorker.DoWork detects that Method1 is returning true. And with the code above, it causes a System.Reflection.TargetInvocationException with addition information Exception has been thrown by the target of an invocation.
The debugger tells me:
this Cannot obtain value of local or argument '<this>' as it is not available at this instruction pointer, possibly because it has been optimized away. System.Delegate
args Cannot obtain value of local or argument 'args' as it is not available at this instruction pointer, possibly because it has been optimized away. object[]
Strangely enough, when I perform (what seems to me) an identical operation with two substrings:
s = s.Substring(s.IndexOf(":"))
s = s.Substring(0, s.IndexOf(">"))
it functions perfectly.
What is the difference between these two methods? Is my inheritance set up incorrectly and that is what is causing these errors? What's going on here?
Let me know if I need to add more code to explain the situation. Thanks.
To get the effect of
s = s.Substring(s.IndexOf(":"))
s = s.Substring(0, s.IndexOf(">"))
in a single statement, you need to calculate the length of the desired substring
s = s.SubString(s.IndexOf(":"), s.IndexOf(">") - s.IndexOf(":"))
Note that if it is possible that the string does not contain a ":" followed later by a ">", you will need to first verify that IndexOf(":") is >= 0 and that s.IndexOf(">") returns a value greater than IndexOf(":").

.Net Error LINQ - new classname with

Why would VS keep saying to add this?
Sub New()
' TODO: Complete member initialization
End Sub
Since you have a constructor that takes parameters, a default, parameterless constructor is not created for you automatically.
Your LINQ statement is not calling your parameterized constructor, it need a parameterless constructor.
Basically, when you code this:
Select New CommunityEvent With {.Day = sRecord(0), etc. }
What gets generated is this
Dim obj As New CommunityEvent() 'Uses parameterless constructor
obj.Day = sRecord(0)
'etc.
When you remove the CommunityEvent With part, then it doesn't use your class, it creates an anonymous type instead.

Passing a method as a parameter .net

I have been searching for quite a while today for an answer to my question but without success. I don't even know if its possible but I'll try my luck here.
Lets say i have this function somewhere in a class:
Public Sub sub1(i as Integer, uc as UserControl)
...
End Sub
And somewhwere else, in an other method i have this call:
sub1(46, new UserControl())
The problem is that i want to pass a UserControl with, lets say, a background colored in blue but it must be defined inside the method call. In other words, i want to pass an object with some properties that are modifed outside the constructor and everything must be done inside the method call. I'm thinking of something like that:
sub1(9387, {Dim uc as new UserControl()
uc.BackColor = Color.Blue
return uc} )
I understand that i could define a UserControl and modify it before the method call but my real situation is way more complex than that. Anyway I just want to know if it is currently possible and if yes show me some examples. In my research i found that i could do some delegate or use some "lambda" expression but I didn't find a solution that perfectly solve my question. And again, I must not write a single character of code outside the method call.
Thanks in advance!
Like this:
sub1(9387, New UserControl With {.BackColor = Color.Blue})
Immediately-invoked functions are possible in VB.NET:
Dim result As Integer = (Function() As Integer
Return 1
End Function)()
Or in your example:
sub1(9387, (Function()
Dim uc As New UserControl()
uc.BackColor = Color.Blue
Return uc
End Function)())
If I'm understanding your question, you can simply use property initializers:
sub1(9387, New UserControl With { .BackColor = Color.Blue })