|
|
|
|
|
by MichaelGG
4325 days ago
|
|
F# will almost definitively help any C# code. Even if you use F# as a "better C#" you'll see improvements. Just removing excessive type annotations is a nice step up in clarity. F#'s benefit will come as a bunch of tiny improvements, "programming in the small" as they call it. For instance: let xs = [ while r.Read() do yield r.GetInt 0 ]
In C#, it's: var xs = new List<int>();
while (r.Read()) { xs.Add(r.GetInt(0)); }
Or: let f x =
let x = try int s with _ -> -1
x * 3
In C#, it's uglier. First because try... isn't an expression. Second, because you cannot shadow variables by rebinding them, so you always have to keep "old" vars around and in scope, and cannot reuse handy variable names: int f(string x) {
int x1;
try { x1 = int.Parse(s); }
catch { x1 = -1; }
return x1 * 3;
}
Or: let x =
use db = new DB()
db.GetX()
In C#, you've got to declare x outside a block: SomeType x;
using(var db = new DB()) {
x = db.GetX()
}
Which is more annoying than it might seem. How much nicer is it to be able to create a new scope at any point in a function, and return a value out of it cleanly?These are by no means a complete or even important showcase of C#'s lacking. Just a few quick thoughts off the top of my head. In general, every time I'm writing C# code, I keep realising how things would be much more concise if I was in F#. |
|
1) Simply write a quick extension method (not ideal but not a reason to switch languages):
2) Simply use the appropriate built-in method: 3) It's a matter of taste. Not a bad feature, but not a killer one either.