C#: Static method parameters?


  • 🚽 Regular

    This is one I've just encountered for the first time in C#.

    I have a number of String commands I can send to a hardware device so I have an enum of the mappings for the commands:

    static class ThingType1 { enum CommandsForThingType1 { DoFooOne = "**--COMMAND1*", DoFooTwo = "**--COMMAND2*", etc... }
    etc...
    

    }

    And then in my transaction state-machine I had a method for doing a command to a thing:

    void DoCommandToThingType1 (String command) { }

    The I had two Things to deal with, each with their own transaction state-machine, and accidentialy did:

    DoCommandToThingType2(CommandsForThingType1.xxx);

    Which obviously wasn't caught as they were both Strings. So I amended it to:

    void DoCommandToThingType1 (CommandsForThingType1 command) { }

    Which failed at compile-time as CommandsForThingType1 is static and this turns out to be designed behaviour. Is there any other way to use a static enum as a method agurement (or a better way to do this)?

    Having to instantiate the class just to provide my immutable ThingX commands and other bits just seems cludgey.

    Edit: I can't get indenting to work in Markup. Sorry, it's ok in the preview.



  • Is the class necessary? You can just put the enum in a namespace directly. Our codebase does this, and you can indeed define a function to take a CommandsForThingType1 param and C# indeed does type-checking.


  • FoxDev

    @Cursorkeys said:

    I can't get indenting to work in Markup

    static class ThingType1
    {
        enum CommandsForThingType1
        {
            DoFooOne = "**--COMMAND1*",
            DoFooTwo = "**--COMMAND2*",
            etc...
        }
        
        etc...
    }
    
    void DoCommandToThingType1 (String command)
    {
    }
    
    DoCommandToThingType2(CommandsForThingType1.xxx);
    
    void DoCommandToThingType1 (CommandsForThingType1 command)
    {
    } 
    

    Easy.

    And don't put the enum in the class.


  • 🚽 Regular

    @blakeyrat said:

    Is the class necessary?

    @RaceProUK said:
    And don't put the enum in the class.

    Thank you very much, that works great. Must be force of habit to jam everything in a class.

    @RaceProUK said:

    Easy.

    Perfect, thank you. It's easy once you see the raw 😄


Log in to reply