-1

I am trying to declare the List like below code.

public List<string> t1,t2,t3 = new List<string>();

When I am trying to add something to List then it gives me error of was null on run time but do not give me compile time error.

public List<string> t1 = new List<string>();
public List<string> t2 = new List<string>();
public List<string> t3 = new List<string>();

While declaration of individual is working perfectly.

Please someone explain this and thank you in advance.

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Shyam
  • 547
  • 4
  • 11
  • 5
    There is nothing to explain, this is basic C# syntax. with `t1,t2,t3 = new...` you only assign the new reference to `t3`, not to `t1` and not to `t2`. To achieve that you'd need `public List t1 = new List(), t3 = new List();` – René Vogt Feb 14 '19 at 15:17
  • 1
    In the first example, you only initialize `t3`? – Rufus L Feb 14 '19 at 15:17
  • In the same way `int a,b,c = 3;` only initializes `c` to `3`, but `a` and `b` are still `0` (the default value). Or actually they are uninitialized. – René Vogt Feb 14 '19 at 15:19
  • @RenéVogt: I would post it as an answer because there is nothing more to say about this than what you already have. – Flater Feb 14 '19 at 15:19
  • 1
    @Flater: Well actually... even if it worked the way OP expected, it still would break his program, because there would be only one List object and three references to it. – Ben Voigt Feb 14 '19 at 15:21
  • 2
    Also, please note that public fields are considered bad practice. You better make them public properties instead. – Zohar Peled Feb 14 '19 at 15:21
  • @BenVoigt: I'm not how that exactly pertains to my comment. But in either case, even if this feature existed, this can be a compiler optimization where it knows to actually instantiate individual objects. I'm not saying that's a given, but it could be equally possible. – Flater Feb 14 '19 at 15:22
  • Perhaps OP - also - expects lists to be immutable? That would explain why having three references to the same list is not a worry, nor having them public. Shyam, List is not immutable. You could look for System.Collections.Immutable.ImmutableList if that is what you want. – Theraot Feb 14 '19 at 15:23
  • Just to add a touch more (from a different perspective). You are declaring three variables of type `List` (`t1`, `t2` and `t3`). You are also creating one object of type `List` with your `new List – Flydog57 Feb 14 '19 at 15:31
  • @Flater: Just that there is in fact more explanation possible. I think Flydog's comment has it pretty comprehensively covered. – Ben Voigt Feb 14 '19 at 15:39

1 Answers1

1

You can declare multiple variables in one line as following IF they are of the same type:

        // Declare and initialize three local variables with same type.
        // ... The type int is used for all three variables.
        //
        int i = 5, y = 10, x = 100;
        Console.WriteLine("{0} {1} {2}", i, y, x);
Kristóf Tóth
  • 791
  • 4
  • 19