fahadash
fahadash

Reputation: 3281

Does F# allows class definition in different files?

I have tried moving my type definition to a different .fs file, I have declared the same namespace in both the files but my code that uses the type won't recognize the type. Does F# allow that ?

Upvotes: 1

Views: 114

Answers (1)

latkin
latkin

Reputation: 16792

As commented, yes this is definitely supported, but there is a requirement (unlike, e.g. C#) that the source file defining your type must be "above" or "before" the source file which consumes it.

So if you have 2 files:

File1.fs

namespace Type.Test    
type Person = { Name : string; Age : int }

File2.fs

namespace Type.Test
module ConsumeType = 
    let richDude : Person = { Name = "Bill"; Age = 58 }

then when the compiler is called on the command line, File1.fs need to be passed first, before File2.fs:

c:\> fsc.exe -a File1.fs File2.fs

If you are in Visual Studio (or some other IDE) to compile, you need to put File1.fs "above" File2.fs:

file order

As mentioned by @Lee in the comments, you can re-order the files in VS by clicking on them and using Alt-Up / Alt-Down.

Upvotes: 3

Related Questions