Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Function with No Paramaters Invoked with Int Should Fail Build

We have a VB.NET project which I am doing some refactoring in. A lot of current functions require a userId to be passed in as a parameter. For example:

Private Function Foo(userId As Integer) As String
    Return "Foo"
End Function

But now, I have made this userId paramater no longer needed in much of our code.

I was thinking I would just remove all the userId parameters from all of the functions that don't need them anymore, and try re-building the project to see what calling code needs to change. To my surprise though, the code built successfully.

I learned that you can call a function which returns a string and doesn't take any parameters, but still pass in an Integer value. VB.NET builds/executes this code as if you were trying to invoke the function and then get the character from the String at the specified index. For example:

Imports System

Public Module MyModule
    Private Function Foo() As String
        Return "Foo"
    End Function

    Public Sub Main()
        Console.WriteLine(Foo(0)) ' prints 'F'
        Console.WriteLine(Foo(1)) ' prints 'o'
    End Sub
End Module

(.NET Fiddle)

I want my build to fail in this case. I have tried using Option Strict On and Option Explicit On but neither seem to change this behaviour.

Is there anyway to make this kind of function invocation invalid in my VB.NET project?

like image 683
Jesse Webb Avatar asked Jan 11 '18 19:01

Jesse Webb


People also ask

How do you pass a parameter to a function in Python?

Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.

What is function parameter in Python?

A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called.

What is the TypeScript type for a function?

Types of Functions in TypeScript: There are two types of functions in TypeScript: Named Function. Anonymous Function.


1 Answers

Create an overload with no parameters which is a copy of the original function in every other respect.

Public Function Foo() As String
    Return "Foo"
End Function

Now change the type of userId to something else (not Object or anything numeric etc.)

Public Function Foo(userId As DateTime) As String
    Return "Foo"
End Function

Since there is an overload with a parameter, the compiler thinks you mean to call that, instead of indexing the chararray. So you have compile errors. Fix the errors

Then delete the original function.

like image 132
djv Avatar answered Sep 30 '22 02:09

djv