Welcome to MSSQL Forum!
MSSQL Forum - Discussions about Microsoft SQL Server

You are currently viewing our community forums as a guest user. Sign up or
Having an account grants you additional privileges, such as creating and participating in discussions.

C# named parameters

Discussion in 'General programming' started by Peter Schmitz, Jun 2, 2017.

  1. Peter Schmitz

    Peter Schmitz Administrator Staff Member

    Something I learned today is the ability to using named parameters when calling a function in C#. While writing T-SQL code, I always like to explicitly name variables, in order to provide transparency to whoever is reading the code.

    Compare this:

    Code (TSQL):

    INSERT INTO TableA
    SELECT * FROM TableB
     
    to this:

    Code (TSQL):

    INSERT INTO TableA
    (
        CustomerName
        , CustomerAddress
        , CustomerCity
        , CustomerZipcode
        , CustomerState
    )
    SELECT
        CustomerName
        , CustomerAddress
        , CustomerCity
        , CustomerZipcode
        , CustomerState
    FROM
        TableB
     
    The latter is far more readable, even with this small of an amount of rows.

    Likewise, in C#, you often end up calling functions, which can have multiple overrides, with any combination of parameters. Turns out you can name the parameters as well for added readability.

    You can do this by adding the variable name followed by a colon :)) in the call. I.e.

    Code (C#):

    MyFunction(parametername: parameter)
     
    Compare this:

    Code (C#):

    string myQueue = channel.QueueDeclare(cQUEUENAME, true, false, false, null);
     
    To this:

    Code (C#):

    string myQueue = channel.QueueDeclare(queue: cQUEUENAME, durable: true, exclusive: false, autoDelete: false, arguments: null);
     
    Both work, but the first syntax requires someone trying to figure out what's going on to spend more time in order to understand the purpose of the variables. The second syntax makes it far more obvious what's going on.

    Another benefit is that you can switch the order of parameters around when using named parameters, as specifying the name will mean the compiler can figure out where the function actually expects them.

    I didn't know this was possible, but will be using this a lot from now on :)

    One drawback I found about is named variables have a negative impact on performance. In case performance is key for your application, you might want to stay away from named variables. However, for my general purposes, the added readability probably outweighs the performance hit incurred.

    I'm interested to hear whether or not this is something you find useful. And, of course, if you suddenly had similar revslations, be sure to share them :)
    Last edited: Jun 2, 2017

Share This Page