C# class variable encapsulation problem?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kenneth6
    New Member
    • Mar 2007
    • 79

    C# class variable encapsulation problem?

    Code:
    public class BUS
    {
    private int m_variable;
    public int variable
    { 
    get { return m_variable; }
    set { m_variable= value; } 
    }
    }
    
    public static void Main()
    {
    BUS[] brand= new BUS[1000];
    for (int i=0; i<1000; i++)
    {
    brand[i].variable = 1000;
    Console.WriteLine(brand[i].variable);
    }
    }
    I encapsulates the code in C# 2005 like this, what;s wrong the codes above? I can't run the program. Error is "An unhandled exception of type 'System.NullRef erenceException ' occurred in ConsoleApplicat ion1.exe". What's wrong with this line "brand[i].variable = 1000;"? I tried to assign the variables there.
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    Place a breakpoint on line 13.
    Step through the code one line at a time (F-10)
    Have the Autos window open.
    You should see exactly which variables are null.
    You can even look down at the values of individual elements of your array.

    Comment

    • artov
      New Member
      • Jul 2008
      • 40

      #3
      The line 16 refers to four named things: :

      1. integer "i"
      2. array "brand"
      3. BUS "band[i]"
      4. property "variable"

      You set the i on line 14 in for -statement.
      You set the brand on line 13.
      You set the brand[i], ..., oh, you don't !!

      So why do you thing the problem is on property variable?

      Add line 15.5 : brand[i] = new BUS();

      Comment

      Working...