18

I am fairly new to functional programming and C#/F#.

What is unclear to me is: Can you do functional programming in C# and/or in F#? Or is it something like, you write some OO code in C#, and some FP code in F#, and use them together?

22

Both F# and C# are .NET languages, meaning they both compile to IL code (which is similar to Java bytecode).

If you write your code to use a specific subset of IL (called CLS compliant - meaning it only uses features that are compatible with all .NET languages), you can use a library written in one .NET language in all other .NET languages.


Now, C# was created as an object oriented language - it has evolved over time and now has some functional features, meaning one can write in a functional style in C#.

F# was created as a functional language. It isn't pure and can have side effects (in particular when using libraries written in other .NET languages, including the base class libraries).


There are no hard rules as to what style to use with which language, but yes, using F# for functional code and C# for OO code makes sense as that is what either language was created for and lends itself to.

And one can use them together, provided the code is written with interoperation in mind (not a hard requirement either, but it can make life easier).

| improve this answer | |
  • 2
    I would argue that F# has better support for the OO paradigm than C# has support for the FP paradigm. – Overly Excessive Dec 30 '14 at 15:22
  • 1
    @OverlyExcessive: Why do you say that? You can be completely functional in C# if you try hard enough. Granted, the syntax for OO is a bit simpler in F#. – Robert Harvey Dec 30 '14 at 16:24
  • 2
    @RobertHarvey Yes but the language lacks built-in support of some very nice FP features like pattern matching and deconstruction. However the contrary does not hold true for F#, it has the same level of OO-support as C# has out of the box. – Overly Excessive Dec 30 '14 at 17:44
  • 1
    @OverlyExcessive: functionalcsharp.codeplex.com – Robert Harvey Dec 30 '14 at 18:41
  • 2
    Truth be told, there are some OO cornercases that are downright clumsy in F#, but that's nothing compared to the type soup you get when you try to do anything slightly non-trivial in C# in a functional way. Func<Func<char, char>, Func<IEnumerable<char>, IEnumerable<char>>>, how do you even read this... – scrwtp Jan 2 '15 at 22:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.