0

I'm somewhat new to programming and I am having trouble just making this work. I'm supposed to run this code using a delegate but I've run into error after error. I'm using Vb.net. Could anyone help me solve the issues in this code?

Public Delegate Function D()
Dim Str As String = Console.ReadLine()
Sub Main()
    Dim D1 As D
    D1 = New D(AddressOf Fn1)
End Sub
Function Fn1()
    System.Console.WriteLine("Please enter the string")

    Dim revstr As String = StrReverse(Str)
    Console.WriteLine("Reverse:")
    Console.WriteLine(revstr)

    Console.WriteLine("Amount of characters in the string:")
    Dim Count As Integer = Str.Length
    Console.WriteLine(Count)

    Console.WriteLine("Amount of words in the string:")
    Dim TempA() As String = Str.Split(" ")
    Console.WriteLine(TempA.Length & " ")
    Console.ReadKey()
End Function

Thanks for any help anyone can give!

4
  • 1
    Not directly to do with your question, but I recommend that you set Option Strict On as the default setting for new projects. Commented Aug 26, 2014 at 14:53
  • Coult you post the errors as well? Commented Aug 26, 2014 at 14:54
  • Function 'Fn1' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. Commented Aug 26, 2014 at 15:00
  • If i switch it from a function to a sub i get this: Method 'Public Sub Fn1()' does not have a signature compatible with delegate 'Delegate Function D() As Object'. Commented Aug 26, 2014 at 15:01

1 Answer 1

3

Your Function Fn1 doesn't return anything.

Functions by definition return something. If you want a method that doesn't return anything you should declare it Sub instead of Function

Your function should also declare the data type is is returning:

Public Function Concat(s1 As String, s2 As String) As String
    return s1 & s2
End Function
Sign up to request clarification or add additional context in comments.

5 Comments

I had it as a sub earlier but i get an error saying that the method and the delegate don't have compatible signatures.
Your delegate needs to be either a Function or a Sub depending on what type of method Fn1 is
I switched the delegate to a sub along with the method but now nothing in the delegate runs. The global readline runs but then it closes.
Thats another question but the answer is that you don't actually do anything with D1 after you have specified the address. Try adding D1.Invoke
Thank you so much for the help its pretty much working how i want it now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.