Hacker News new | past | comments | ask | show | jobs | submit login

One of the things I wish C# did was allow for inline declaration of enumerations in method parameters.

Something like:

    void DoSomething(Thing thing, enum logging{WithLogging,NoLogging}){}
Because I'd frequently like to be able to make my parameters more explicit, but the overhead of creating a new enum type seems a tad heavyweight.

Edit: Raised it as an issue on GitHub with more details - https://github.com/dotnet/roslyn/issues/3497




Ocaml can do this

  let do_something (thing : Thing.t) (logging : [`With_logging | `No_logging])  =
  ...
Even better, it can even infer the type based on you using it (for example matching on it):

  let do_something thing logging =
    let logging_as_bool = 
      match logging with
      | `With_logging -> true
      | `No_logging -> false
    in
    ....


Why not just use named parameters at the call site instead?

    DoSomething(thing, logging: true);


I definitely like this approach in my own code. I think the main advantage of a different approach such as enums is enforcing the explicitness at the call site for all users, especially in library functions.

Another thing to consider: In some cases, it may make more sense to split the function into two versions, one for 'true' and one for 'false'. Then you gain the enforced explicitness. The function could call a private method to share code and pass the Boolean. Clearly that isn't ideal for all situations, but it might help in some situations today.


> Another thing to consider: In some cases, it may make more sense to split the function into two versions, one for 'true' and one for 'false'. Then you gain the enforced explicitness. The function could call a private method to share code and pass the Boolean.

The author describes exactly this approach and implementation, under the heading "Distinct functions".


That's what we usually do in C#.

Required parameters as positional, and optional as named.

doSomething(req_param_1_value, req_param_2_value, optional_param_1 : value, optional_param2: value);


That's a nice idea. It'd also limit the scope so it has a short name, instead of something like `DoSomethingLogging`.


Honestly, this is a really nice piece of notation -- I'd really like to see this in C++ (just because that's the language I personally use the most).




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: