Search code examples
c#access-modifiersclass-members

Accessibility of multiple fields declared at the same line


I wonder if I do this all the variables will be public or just the first one:

public string equipamento, marca, modelo, descricao, observacoes, prioridade;

Or if I need to declare them like this:

public string equipamento;
public string marca;
public string modelo; 
[...]

The second option obviously works, but does the first one too?


Solution

  • As explained in the C# language specification, section 10.4 Fields on MSDN:

    A field declaration that declares multiple fields is equivalent to multiple declarations of single fields with the same attributes, modifiers, and type. For example

    class A
    {
       public static int X = 1, Y, Z = 100;
    }
    

    is equivalent to

    class A
    {
       public static int X = 1;
       public static int Y;
       public static int Z = 100;
    }
    

    But as commented by @hyde, consider the former bad practice. It actively harms the readability of your code.