0

In F#, we can override System.Object methods when creating new object instances with object expressions. This can be very useful when one wants to quickly print with the ToString() method:

let obj = { new System.Object() with member x.ToString() = "F#" }
printfn "%A" obj

However, when should I need to create new objects in C#, beside lock statements?

var obj = new object();
Console.WriteLine(obj);
MiP
  • 5,846
  • 3
  • 26
  • 41
  • I don't know. Have you come across a specific example you'd like to share with us? – JLRishe Dec 26 '17 at 13:07
  • Beside lock statements it's not really useful to instantiate `object`... You can use an `object` instance as a token for comparison but that's about it. – Lucas Trzesniewski Dec 26 '17 at 13:09
  • No, apart from using it as a private synchronization object, AFAIK there is really no use for a runtime `object` typed instance. But that’s true for F# too, the moment you override functionality it stops being an `object` doesn’t it? The only difference is the convenient syntax F# provides. – InBetween Dec 26 '17 at 13:15
  • @InBetween is right. You can make your own code to get syntax in C# similar to the F# you show. For example with [Moq](https://github.com/moq/moq4), you can say `var obj = Mock.Of(x => x.ToString() == "F#");` and `var` will stand for `System.Object`, the compile-time type of the mock. Of course the run-time type, as seen with `obj.GetType().ToString()` for example, will be something inheriting from `System.Object`. – Jeppe Stig Nielsen Dec 26 '17 at 13:25

0 Answers0