Tesrt B

Tesrt B

  • NA
  • 1
  • 1.4k

foreach passes object by value?

Nov 3 2011 1:09 PM
Look at the following code snippet  

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication2

{

    class Program

    {

        static void Main(string[] args)

        {

            Test test = new Test();

            test.listOfListInListObjects = new List<TestInTest>();

            test.listOfListInListObjects.Add(new TestInTest());

            test.listOfListInListObjects.Add(new TestInTest());

            populateValues(ref test);

        }

 

        public static void populateValues(ref Test testObject)

        {

            testObject.Populate();

            Console.WriteLine("Program: "+testObject.listOfListInListObjects[0].Test);

/*why does this print empty string?? I am changing this to for loop and seeing if it changes . */

        }

    }

 

    struct Test

    {

        public List<TestInTest> listOfListInListObjects;

 

        public void Populate()

        {

            foreach (var listOfListInListObject in listOfListInListObjects)

            {

                listOfListInListObject.Populate();

                Console.WriteLine(listOfListInListObject.Test);

            }

        }

    }

 

    struct TestInTest

    {

        private string test;

 

        public string Test

        {

            get { return test; }

            private set { test = value; }

        }

 

        public void Populate()

        {

            this.Test = "abc";

}

       

Answers (1)