Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. A question about references

A question about references

Scheduled Pinned Locked Moved C#
csharpperformancequestion
10 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • 6 Offline
    6 Offline
    6 921 364 and growing
    wrote on last edited by
    #1

    In C# - Classes are reference types; structures are value types. I was reading about this and saw something which I didn't understand. I have created a simple program to explain my doubt. In this program I have defined a class and a structure with an integer variable.

    class TestClass
    {
    public int x;
    }
    struct TestStruct
    {
    public int x;
    }

    Now I have couple of static methods each changing the value of the integer.

    static void ChangeStruct(TestStruct ts)
    {
    ts.x = 10;
    }
    static void ChangeClass(TestClass tc)
    {
    tc.x = 10;
    //tc = null;
    }

    Now in the main method, I call this functions and results are as expected.

    static void Main(string[] args)
    {
    TestStruct ts = new TestStruct();
    ts.x = 20;
    Console.WriteLine("Before change: ts is ({0})", ts.x);
    ChangeStructure(ts);
    Console.WriteLine("After method: ts is ({0)", ts.x);
    TestClass tc = new TestClass();
    tc.x = 20;
    Console.WriteLine("Before method: tc is ({0})", tc.x);
    ChangeClass(tc);
    Console.WriteLine("After method: tc is ({0})", tc.x);
    Console.ReadLine();
    }

    So far so good. Now when I uncomment the line tc = null; in the method ChangeClass, I expect the class to be null referenced i.e it should not reference to any memory in the heap any more. But that is not how it works. Can anybody explain me why there is a different behaviour here. Thanks a lot!

    R I V 3 Replies Last reply
    0
    • 6 6 921 364 and growing

      In C# - Classes are reference types; structures are value types. I was reading about this and saw something which I didn't understand. I have created a simple program to explain my doubt. In this program I have defined a class and a structure with an integer variable.

      class TestClass
      {
      public int x;
      }
      struct TestStruct
      {
      public int x;
      }

      Now I have couple of static methods each changing the value of the integer.

      static void ChangeStruct(TestStruct ts)
      {
      ts.x = 10;
      }
      static void ChangeClass(TestClass tc)
      {
      tc.x = 10;
      //tc = null;
      }

      Now in the main method, I call this functions and results are as expected.

      static void Main(string[] args)
      {
      TestStruct ts = new TestStruct();
      ts.x = 20;
      Console.WriteLine("Before change: ts is ({0})", ts.x);
      ChangeStructure(ts);
      Console.WriteLine("After method: ts is ({0)", ts.x);
      TestClass tc = new TestClass();
      tc.x = 20;
      Console.WriteLine("Before method: tc is ({0})", tc.x);
      ChangeClass(tc);
      Console.WriteLine("After method: tc is ({0})", tc.x);
      Console.ReadLine();
      }

      So far so good. Now when I uncomment the line tc = null; in the method ChangeClass, I expect the class to be null referenced i.e it should not reference to any memory in the heap any more. But that is not how it works. Can anybody explain me why there is a different behaviour here. Thanks a lot!

      R Offline
      R Offline
      Rob Philpott
      wrote on last edited by
      #2

      That's because tc is a reference type passed by value, ie. a local copy. Setting it to null in the static will not change the value outside the method. Stick the word 'ref' in front of it and you'll probably get the behaviour you're expecting.

      Regards, Rob Philpott.

      6 2 Replies Last reply
      0
      • 6 6 921 364 and growing

        In C# - Classes are reference types; structures are value types. I was reading about this and saw something which I didn't understand. I have created a simple program to explain my doubt. In this program I have defined a class and a structure with an integer variable.

        class TestClass
        {
        public int x;
        }
        struct TestStruct
        {
        public int x;
        }

        Now I have couple of static methods each changing the value of the integer.

        static void ChangeStruct(TestStruct ts)
        {
        ts.x = 10;
        }
        static void ChangeClass(TestClass tc)
        {
        tc.x = 10;
        //tc = null;
        }

        Now in the main method, I call this functions and results are as expected.

        static void Main(string[] args)
        {
        TestStruct ts = new TestStruct();
        ts.x = 20;
        Console.WriteLine("Before change: ts is ({0})", ts.x);
        ChangeStructure(ts);
        Console.WriteLine("After method: ts is ({0)", ts.x);
        TestClass tc = new TestClass();
        tc.x = 20;
        Console.WriteLine("Before method: tc is ({0})", tc.x);
        ChangeClass(tc);
        Console.WriteLine("After method: tc is ({0})", tc.x);
        Console.ReadLine();
        }

        So far so good. Now when I uncomment the line tc = null; in the method ChangeClass, I expect the class to be null referenced i.e it should not reference to any memory in the heap any more. But that is not how it works. Can anybody explain me why there is a different behaviour here. Thanks a lot!

        I Offline
        I Offline
        Ian Shlasko
        wrote on last edited by
        #3

        Simple... The key is the way you pass the reference to ChangeClass. When you do ChangeClass(tc), you're only sending a reference to tc... You're telling ChangeClass where, in memory, it can find the data in tc. And since you didn't specify the ref keyword when passing it to ChangeClass, you're just sending a COPY of the reference, not the original variable. As an analogy... I have the URL to a website, and I e-mail it to you. You erase your e-mail, but you haven't erased my copy of the URL, just your own.

        Proud to have finally moved to the A-Ark. Which one are you in?
        Author of the Guardians Saga (Sci-Fi/Fantasy novels)

        6 1 Reply Last reply
        0
        • 6 6 921 364 and growing

          In C# - Classes are reference types; structures are value types. I was reading about this and saw something which I didn't understand. I have created a simple program to explain my doubt. In this program I have defined a class and a structure with an integer variable.

          class TestClass
          {
          public int x;
          }
          struct TestStruct
          {
          public int x;
          }

          Now I have couple of static methods each changing the value of the integer.

          static void ChangeStruct(TestStruct ts)
          {
          ts.x = 10;
          }
          static void ChangeClass(TestClass tc)
          {
          tc.x = 10;
          //tc = null;
          }

          Now in the main method, I call this functions and results are as expected.

          static void Main(string[] args)
          {
          TestStruct ts = new TestStruct();
          ts.x = 20;
          Console.WriteLine("Before change: ts is ({0})", ts.x);
          ChangeStructure(ts);
          Console.WriteLine("After method: ts is ({0)", ts.x);
          TestClass tc = new TestClass();
          tc.x = 20;
          Console.WriteLine("Before method: tc is ({0})", tc.x);
          ChangeClass(tc);
          Console.WriteLine("After method: tc is ({0})", tc.x);
          Console.ReadLine();
          }

          So far so good. Now when I uncomment the line tc = null; in the method ChangeClass, I expect the class to be null referenced i.e it should not reference to any memory in the heap any more. But that is not how it works. Can anybody explain me why there is a different behaviour here. Thanks a lot!

          V Offline
          V Offline
          V 0
          wrote on last edited by
          #4

          mmm, you're not rendering the class itself to null I think, rather the parameter tc. Since it is a reference it should be the same object, but maybe .Net does something funky when the parameter passed to a method is the same type as the class. I don't know for sure, but it could be. Try passing the object with the ref keyword (need to change method signature as well).

          V.

          I 1 Reply Last reply
          0
          • V V 0

            mmm, you're not rendering the class itself to null I think, rather the parameter tc. Since it is a reference it should be the same object, but maybe .Net does something funky when the parameter passed to a method is the same type as the class. I don't know for sure, but it could be. Try passing the object with the ref keyword (need to change method signature as well).

            V.

            I Offline
            I Offline
            Ian Shlasko
            wrote on last edited by
            #5

            V. wrote:

            Since it is a reference it should be the same object, but maybe .Net does something funky when the parameter passed to a method is the same type as the class.

            Function arguments are always passed by value unless the ref keyword is used.

            Proud to have finally moved to the A-Ark. Which one are you in?
            Author of the Guardians Saga (Sci-Fi/Fantasy novels)

            1 Reply Last reply
            0
            • R Rob Philpott

              That's because tc is a reference type passed by value, ie. a local copy. Setting it to null in the static will not change the value outside the method. Stick the word 'ref' in front of it and you'll probably get the behaviour you're expecting.

              Regards, Rob Philpott.

              6 Offline
              6 Offline
              6 921 364 and growing
              wrote on last edited by
              #6

              Thank you for answering.

              Rob Philpott wrote:

              That's because tc is a reference type passed by value, ie. a local copy

              I do understand that, but what confuses me is why the values are changed then. I see an inconsistency in the behaviour. Since the memory reference is passed, if we are changing the value in the method, it is getting changed and assigning a null doesn't.

              Rob Philpott wrote:

              Stick the word 'ref' in front of it and you'll probably get the behaviour you're expecting.

              Yes that will do the job.

              1 Reply Last reply
              0
              • I Ian Shlasko

                Simple... The key is the way you pass the reference to ChangeClass. When you do ChangeClass(tc), you're only sending a reference to tc... You're telling ChangeClass where, in memory, it can find the data in tc. And since you didn't specify the ref keyword when passing it to ChangeClass, you're just sending a COPY of the reference, not the original variable. As an analogy... I have the URL to a website, and I e-mail it to you. You erase your e-mail, but you haven't erased my copy of the URL, just your own.

                Proud to have finally moved to the A-Ark. Which one are you in?
                Author of the Guardians Saga (Sci-Fi/Fantasy novels)

                6 Offline
                6 Offline
                6 921 364 and growing
                wrote on last edited by
                #7

                Thanks, that very much clears the doubt. Please see what I got is correct: I have a reference stored to the object of the TestClass on the stack. When I pass this to the method ChangeClass, I just pass a value which refers to a memory location which is same as the actual memory location of the object. So any change to the fields of the class is reflected as the method is accessing the same memory location. When I assign the object null in the method, the reference to the object is no more available to the method. But it is still available to the Main method. This is my understanding. Please let me know if I am wrong somewhere. Thanks and voted as a "good answer". PS: I am changing the message type to answer as it contains descriptive answer.

                I 1 Reply Last reply
                0
                • R Rob Philpott

                  That's because tc is a reference type passed by value, ie. a local copy. Setting it to null in the static will not change the value outside the method. Stick the word 'ref' in front of it and you'll probably get the behaviour you're expecting.

                  Regards, Rob Philpott.

                  6 Offline
                  6 Offline
                  6 921 364 and growing
                  wrote on last edited by
                  #8

                  Ron, I was thinking upon Ian's answer and finally understood the concept. You may like to check my reply to Ian. Thanks for your help. Since your answer is also correct, I am voting it up. :thumbsup:

                  1 Reply Last reply
                  0
                  • 6 6 921 364 and growing

                    Thanks, that very much clears the doubt. Please see what I got is correct: I have a reference stored to the object of the TestClass on the stack. When I pass this to the method ChangeClass, I just pass a value which refers to a memory location which is same as the actual memory location of the object. So any change to the fields of the class is reflected as the method is accessing the same memory location. When I assign the object null in the method, the reference to the object is no more available to the method. But it is still available to the Main method. This is my understanding. Please let me know if I am wrong somewhere. Thanks and voted as a "good answer". PS: I am changing the message type to answer as it contains descriptive answer.

                    I Offline
                    I Offline
                    Ian Shlasko
                    wrote on last edited by
                    #9

                    100% correct.

                    Proud to have finally moved to the A-Ark. Which one are you in?
                    Author of the Guardians Saga (Sci-Fi/Fantasy novels)

                    6 1 Reply Last reply
                    0
                    • I Ian Shlasko

                      100% correct.

                      Proud to have finally moved to the A-Ark. Which one are you in?
                      Author of the Guardians Saga (Sci-Fi/Fantasy novels)

                      6 Offline
                      6 Offline
                      6 921 364 and growing
                      wrote on last edited by
                      #10

                      Thanks a lot!

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups