views:

152

answers:

2

I want to program something in both C# and F#. I have partial classes and i would like to define F# methods in a few of them. I get the issue that a partial class can not be spanned across 2 DLLs. Is there a way i can merged them? I prefer a free solution and the ability to do it automatically in a normal build.

+6  A: 

You cannot write different parts of a class in different languages.

What are you trying to do?

You could expose methods in a separate F# library and call them from the class in C#.
You could then use ILMerge to merge the two assemblies.

SLaks
Before downvoting this, note that ILMerge will not help at all.
SLaks
I have a BasicUser class with database connections and other great things like useridFromName VerifiedUser (and admin). I'd like a few functions in F# which uses many of those functions (normally they be part of the partial class) and i would like to be write methods in F# unless its too complicated for me which i'll then do in C# and lose little development time.
acidzombie24
Won't it work with ildasm->merge->ilasm?
Vlad
@Vlad: No. It won't.
SLaks
+3  A: 

I already heared a request like this, so it seems that more people would like to do this. However, as already said, this isn't possible. You can use ILMerge to merge multiple assemblies (with distinct classes), but it isn't possible to write different parts of a class in a different language. The only answer you can get is that you'll need to structure your code differently. There are several options:

  • Declare an F# module with functions that contian the parts you want to do in F#
  • Declare types with members in F# and then use these classes from C#
  • Declare a base class in C# (or F#) and create an inherited class that adds the rest of the functionality in the other language.

In any case, you'll need to decouple the functionality in some way (which is technical requirement and I believe that it will also help making your code more readable).

To demonstrate why partial classes across multiple assemblies cannot work:

// C# part
partial class Foo { 
  private int csharpField;
  int Bar() { return FSharpMethod(); }
}

// F# part
type Foo =
  member x.FSharpMethod() = x.csharpField

In this example, C# cannot compile the code, because it doesn't know whether FSharpMethod exists and what is its type. The F# compiler also cannot compile the code, because it doesn't know what is the type of csharpField (and whether it exists).

Of course, this is just an example of one technical problem, but there would be many of them - you can easily imagine numerous other problems that would arise if you wanted to support this (and it seems that the two compilers would need to be aware of the other one's internals).

Tomas Petricek
comments made in Henk Holterman has additional reasons why this wont work.
acidzombie24