Search code examples
f#unit-type

F# This expression should have type 'unit', but has type 'bool'


I have the following code

if somecondition then
  myobj.Property1 = match myobj.Property1 with
                       | null -> SomePropertyType ()
                       | p -> p

What I am trying to do is to see if myobj.Property1 is null, if it is not then leave it alone otherwise create a new object of type SomePropertyType and assign it.

Problem is, I am getting a

This expression should have type 'unit', but has type 'bool'

And what should I do If I had to put multiple of those myobj.Property1 .... statements under that if ?


Solution

  • You are comparing two values (using =) so the return type will be bool, but if you have an if without else the compiler expect unit as return type.

    I guess you intended to assign the value to the property, use <- instead:

    if somecondition then
        myobj.Property1 <- match myobj.Property1 with ...
    

    Anyway if you want to check for null to assign a default value you don't need a match, an if then is enough:

    if somecondition then
        if (myobj.Property1 = null) then myobj.Property1 <- SomePropertyType ()
        ...
    

    UPDATE

    You can "merge" both if .. then to a single match:

    match (somecondition, myobj.Property1) with
    | true, null -> myobj.Property1 <- SomePropertyType ()
    ...