0

This is really a .NET question, but I am wondering what the answer is. I've read before that closures are compiled to .NET classes under the hood.

Generally it would depend on the implementation, but I would be surprised to learn that this part would not be optimized in VS2015.

Edit: This question is not a duplicate because it is not asking what a closure is, but about a implementation detail about them.

Edit2:

let math_func a =
    let mutable a = a

    let add b = a <- a + b
    let mult b = a <- a * b
    let div b = a <- a / b
    let ret () = a
    add, mult, div, ret

let add, mult, div, ret = math_func 5
add 5
ret()
mult 4
ret()
div 2
ret()

Here is a shortish F# example, with all the functions enclosing the same variable. I can think of more complex examples, but the ones I am using in a game project instead of virtual functions are not much more complicated.

I've never really realized how much they can replace with regards to object oriented programming and I am wondering how far I can go with this. They are also neat as they allow me to defer thinking about how to exactly design my program.

Marko Grdinić
  • 3,798
  • 3
  • 18
  • 21
  • 1
    Possible duplicate of [http://stackoverflow.com/questions/428617/what-are-closures-in-net](http://stackoverflow.com/questions/428617/what-are-closures-in-net) – Dbuggy Jan 21 '16 at 15:42
  • 1
    Why don't you try it and see? You could at least give an example of exactly what you mean. (The exact details will depend on scope, what's used by the closures etc.) – Jon Skeet Jan 21 '16 at 15:42
  • @JonSkeet Added an example as per request. – Marko Grdinić Jan 21 '16 at 15:59
  • Well that's F#... I can only speak to what the C# compiler would do. This will be language as well as compiler specific. – Jon Skeet Jan 21 '16 at 16:10

0 Answers0