Search code examples
vb.netnullablemethod-chaining

Nullable method-chaining with ?-Operator


I thought I can chain methods/properties on Nullable Types using the ?-Operator like so

Dim foo As SomeObject? = New SomeObject()
Dim bar As SomeObject? = Nothing
foo?.SomeProperty 'Returns a value
bar?.someProperty 'Returns Nothing

However, given the following special example

Structure Foo
  Public Sub New(bar As Integer)
    Me.Bar = bar
  End Sub
  Property Bar() As Integer
  Public Shared Operator +(f1 As Foo, f2 As Foo) As Foo
    Return New Foo(f1.Bar + f2.Bar)
  End Operator
End Structure

I get an error after performing the following Operation

Dim baz1 As Foo? = New Foo(13)
Dim baz2 As Foo? = New Foo(37)
Dim baz3 = baz1 + baz2
baz3?.Bar 'error BC36637: The '?' character cannot be used here

Why is that so and more important how can I achieve the behaviour shown in my first example at the top?


Solution

  • Main issue after testing:

    I copied your exact code into VS2015 and tested it. The issue is because you are attempting to call a property, but are not doing anything with it.

    You cannot just call a property. You either need to write to it or read from it. The below works just fine.

    Dim baz1 As Foo? = New Foo(13)
    Dim baz2 As Foo? = New Foo(37)
    Dim baz3 = baz1 + baz2
    
    Dim fooBar = baz3?.Bar
    

    If I actually add a method, it too will work:

    Dim baz1 As Foo? = New Foo(13)
    Dim baz2 As Foo? = New Foo(37)
    Dim baz3 = baz1 + baz2
    baz3?.FooBar()
    

    The actual error I got with your code was:

    BC30545: Property access must assign to the property or use its value.

    Old thought:

    The issue is with your Operator + overload. You returned a standard struct instance. This is not nullable. Therefore, you cannot use the ? operator as it will never be null and isn't nullable.

    Public Shared Operator +(f1 As Foo, f2 As Foo) As Foo
        Return New Foo(f1.Bar + f2.Bar)
    End Operator
    

    You may be able to get it to work (untested) by changing your declaration to:

    Dim baz3 As Foo? = baz1 + baz2
    

    But even then that may not work because baz1+baz2 currently will also never be null.