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. Should we use 'ref' keyword while passing objects also...

Should we use 'ref' keyword while passing objects also...

Scheduled Pinned Locked Moved C#
question
9 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.
  • S Offline
    S Offline
    Spunky Coder
    wrote on last edited by
    #1

    Hi , I've read that objects are reference types and also that 'ref' keyword is used to pass the reference of a value ... Now plz look into the following examples... namespace ExampleConsoleApp { public class Program { static void Main(string[] args) { Manager emp = new Manager(); changevalue(emp); Console.Out.WriteLine(" " + emp.name); Console.Read(); } public static void changevalue(Manager man) { man.name = "Grade1Employee"; } } public class Manager { public string name = string.Empty; } } The program gives the output as "Grade1Employee" .... Example2 namespace ExampleConsoleApp { public class Program { static void Main(string[] args) { Manager emp = new Manager(); emp.Name="Grade1Employee"; changevalue(emp); Console.Out.WriteLine(" " + emp.name); Console.Read(); } public static void changevalue(Manager man) { Manager emp2 = new Manager(); emp2.name = "TopLevelEmployee"; man = emp2; } } public class Manager { public string name = string.Empty; } } ..The above still gives the output as "Grade1Employee" why is it so? When object is a reference type then the value should be changed right?...when use a ref keyword for the parameter name in the method like "changevalue(ref Manager man)" then the output is "TopLevelEmployee"... Why is it behaving differently in two cases..?

    Koushik

    D S L S 4 Replies Last reply
    0
    • S Spunky Coder

      Hi , I've read that objects are reference types and also that 'ref' keyword is used to pass the reference of a value ... Now plz look into the following examples... namespace ExampleConsoleApp { public class Program { static void Main(string[] args) { Manager emp = new Manager(); changevalue(emp); Console.Out.WriteLine(" " + emp.name); Console.Read(); } public static void changevalue(Manager man) { man.name = "Grade1Employee"; } } public class Manager { public string name = string.Empty; } } The program gives the output as "Grade1Employee" .... Example2 namespace ExampleConsoleApp { public class Program { static void Main(string[] args) { Manager emp = new Manager(); emp.Name="Grade1Employee"; changevalue(emp); Console.Out.WriteLine(" " + emp.name); Console.Read(); } public static void changevalue(Manager man) { Manager emp2 = new Manager(); emp2.name = "TopLevelEmployee"; man = emp2; } } public class Manager { public string name = string.Empty; } } ..The above still gives the output as "Grade1Employee" why is it so? When object is a reference type then the value should be changed right?...when use a ref keyword for the parameter name in the method like "changevalue(ref Manager man)" then the output is "TopLevelEmployee"... Why is it behaving differently in two cases..?

      Koushik

      D Offline
      D Offline
      DavidNohejl
      wrote on last edited by
      #2

      Spunky Coder wrote:

      public static void changevalue(Manager man) { Manager emp2 = new Manager(); emp2.name = "TopLevelEmployee"; man = emp2; }

      This is correct. Objects are passed as reference, but that means that instead of copying whole object, reference to object is copied.

      changevalue(Manager man) <- copy of "pointer" to instance Manager
      {
      
      Manager emp2 = new Manager(); <- local variable
      emp2.name = "TopLevelEmployee"; <- you do changes to local variable
      
      man = emp2; <- you assign the copy of pointer to instance to local instance
      
      
      } <- all is forgotten when method returns
      

      Why is that called passing by reference? If it was passed by value, following code: changevalue(Manager man) <- copy of instance of Manager { man.name = "TopLevelEmployee"; <- you do changes to copy } would NOT change name of man outside the method. As you can try, it indeed does change the name, because objects are passed by reference. If you really want to change the reference to man, use keyword ref. (think about pointer to pointer)


      [My Blog]
      "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
      "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

      S 1 Reply Last reply
      0
      • S Spunky Coder

        Hi , I've read that objects are reference types and also that 'ref' keyword is used to pass the reference of a value ... Now plz look into the following examples... namespace ExampleConsoleApp { public class Program { static void Main(string[] args) { Manager emp = new Manager(); changevalue(emp); Console.Out.WriteLine(" " + emp.name); Console.Read(); } public static void changevalue(Manager man) { man.name = "Grade1Employee"; } } public class Manager { public string name = string.Empty; } } The program gives the output as "Grade1Employee" .... Example2 namespace ExampleConsoleApp { public class Program { static void Main(string[] args) { Manager emp = new Manager(); emp.Name="Grade1Employee"; changevalue(emp); Console.Out.WriteLine(" " + emp.name); Console.Read(); } public static void changevalue(Manager man) { Manager emp2 = new Manager(); emp2.name = "TopLevelEmployee"; man = emp2; } } public class Manager { public string name = string.Empty; } } ..The above still gives the output as "Grade1Employee" why is it so? When object is a reference type then the value should be changed right?...when use a ref keyword for the parameter name in the method like "changevalue(ref Manager man)" then the output is "TopLevelEmployee"... Why is it behaving differently in two cases..?

        Koushik

        S Offline
        S Offline
        Stefan Troschuetz
        wrote on last edited by
        #3

        Spunky Coder wrote:

        The above still gives the output as "Grade1Employee" why is it so?

        You're passing a reference to a Manager object to the method. If you change the object via this reference the changes reflect outside the method (first example). If you create a new object and assign the reference to it to the method parameter, then this change does not reflect outside the method (second example), because changes to parameters (values or references) do not reflect outside a method unless you use the ref or out keyword.


        "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning." - Rick Cook

        www.troschuetz.de

        1 Reply Last reply
        0
        • S Spunky Coder

          Hi , I've read that objects are reference types and also that 'ref' keyword is used to pass the reference of a value ... Now plz look into the following examples... namespace ExampleConsoleApp { public class Program { static void Main(string[] args) { Manager emp = new Manager(); changevalue(emp); Console.Out.WriteLine(" " + emp.name); Console.Read(); } public static void changevalue(Manager man) { man.name = "Grade1Employee"; } } public class Manager { public string name = string.Empty; } } The program gives the output as "Grade1Employee" .... Example2 namespace ExampleConsoleApp { public class Program { static void Main(string[] args) { Manager emp = new Manager(); emp.Name="Grade1Employee"; changevalue(emp); Console.Out.WriteLine(" " + emp.name); Console.Read(); } public static void changevalue(Manager man) { Manager emp2 = new Manager(); emp2.name = "TopLevelEmployee"; man = emp2; } } public class Manager { public string name = string.Empty; } } ..The above still gives the output as "Grade1Employee" why is it so? When object is a reference type then the value should be changed right?...when use a ref keyword for the parameter name in the method like "changevalue(ref Manager man)" then the output is "TopLevelEmployee"... Why is it behaving differently in two cases..?

          Koushik

          L Offline
          L Offline
          laserbaronen
          wrote on last edited by
          #4

          When you take (Manager man) as input, you are actually taking a copy of the pointer to the actual manager. that means it points to the same object, but you cannot change the pointer adress declared in main, to do that you need the ref.. dunno if you get what i mean tho, im not good at explaining ^^ Manager man <- pointer to a manager object = new Manager() <- returns adress to the new object

          fafafa, ringakta icke sådant som bringa ack så naggande högönsklig välmåga å baronens ära.

          1 Reply Last reply
          0
          • D DavidNohejl

            Spunky Coder wrote:

            public static void changevalue(Manager man) { Manager emp2 = new Manager(); emp2.name = "TopLevelEmployee"; man = emp2; }

            This is correct. Objects are passed as reference, but that means that instead of copying whole object, reference to object is copied.

            changevalue(Manager man) <- copy of "pointer" to instance Manager
            {
            
            Manager emp2 = new Manager(); <- local variable
            emp2.name = "TopLevelEmployee"; <- you do changes to local variable
            
            man = emp2; <- you assign the copy of pointer to instance to local instance
            
            
            } <- all is forgotten when method returns
            

            Why is that called passing by reference? If it was passed by value, following code: changevalue(Manager man) <- copy of instance of Manager { man.name = "TopLevelEmployee"; <- you do changes to copy } would NOT change name of man outside the method. As you can try, it indeed does change the name, because objects are passed by reference. If you really want to change the reference to man, use keyword ref. (think about pointer to pointer)


            [My Blog]
            "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
            "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

            S Offline
            S Offline
            Spunky Coder
            wrote on last edited by
            #5

            Hi.. changevalue(Manager man) <- copy of "pointer" to instance Manager { Manager emp2 = new Manager(); <- local variable emp2.name = "TopLevelEmployee"; <- you do changes to local variable man = emp2; <- you assign the copy of pointer to instance to local instance } <- all is forgotten when method returns ...Now so what's the difference between passing an int datatype and object when its scope is just limited to the called function ?...

            Koushik

            D 1 Reply Last reply
            0
            • S Spunky Coder

              Hi.. changevalue(Manager man) <- copy of "pointer" to instance Manager { Manager emp2 = new Manager(); <- local variable emp2.name = "TopLevelEmployee"; <- you do changes to local variable man = emp2; <- you assign the copy of pointer to instance to local instance } <- all is forgotten when method returns ...Now so what's the difference between passing an int datatype and object when its scope is just limited to the called function ?...

              Koushik

              D Offline
              D Offline
              DavidNohejl
              wrote on last edited by
              #6

              Spunky Coder wrote:

              ...Now so what's the difference between passing an int datatype and object when its scope is just limited to the called function ?...

              No, scope of the reference is limited to called function. Actual instance of object you change via the reference will keep the changes outside that function. Is this what you mean?


              [My Blog]
              "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
              "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

              S 1 Reply Last reply
              0
              • S Spunky Coder

                Hi , I've read that objects are reference types and also that 'ref' keyword is used to pass the reference of a value ... Now plz look into the following examples... namespace ExampleConsoleApp { public class Program { static void Main(string[] args) { Manager emp = new Manager(); changevalue(emp); Console.Out.WriteLine(" " + emp.name); Console.Read(); } public static void changevalue(Manager man) { man.name = "Grade1Employee"; } } public class Manager { public string name = string.Empty; } } The program gives the output as "Grade1Employee" .... Example2 namespace ExampleConsoleApp { public class Program { static void Main(string[] args) { Manager emp = new Manager(); emp.Name="Grade1Employee"; changevalue(emp); Console.Out.WriteLine(" " + emp.name); Console.Read(); } public static void changevalue(Manager man) { Manager emp2 = new Manager(); emp2.name = "TopLevelEmployee"; man = emp2; } } public class Manager { public string name = string.Empty; } } ..The above still gives the output as "Grade1Employee" why is it so? When object is a reference type then the value should be changed right?...when use a ref keyword for the parameter name in the method like "changevalue(ref Manager man)" then the output is "TopLevelEmployee"... Why is it behaving differently in two cases..?

                Koushik

                S Offline
                S Offline
                Spunky Coder
                wrote on last edited by
                #7

                Suppose we alter the first example as following... public static void changevalue(Manager man) { man.name = "Grade1Employee"; man = null; } still the emp.name in the main function gives the value "Grade1Employee"....Now when we are assigning a value to the member of the object (to the reference copy of the object) , the value is retained and when are setting the reference copy to null the value is not retained.... :(

                Koushik

                1 Reply Last reply
                0
                • D DavidNohejl

                  Spunky Coder wrote:

                  ...Now so what's the difference between passing an int datatype and object when its scope is just limited to the called function ?...

                  No, scope of the reference is limited to called function. Actual instance of object you change via the reference will keep the changes outside that function. Is this what you mean?


                  [My Blog]
                  "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
                  "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

                  S Offline
                  S Offline
                  Spunky Coder
                  wrote on last edited by
                  #8

                  I'm totally confused...:^) ...i was taught that both in java and c# objects are referenced types so when we do any operations on the object they get reflected to entire object wherever you access it ..but now its behaving differently...

                  Koushik

                  D 1 Reply Last reply
                  0
                  • S Spunky Coder

                    I'm totally confused...:^) ...i was taught that both in java and c# objects are referenced types so when we do any operations on the object they get reflected to entire object wherever you access it ..but now its behaving differently...

                    Koushik

                    D Offline
                    D Offline
                    DavidNohejl
                    wrote on last edited by
                    #9

                    Spunky Coder wrote:

                    i was taught that both in java and c# objects are referenced types so when we do any operations on the object they get reflected to entire object wherever you access it

                    But you are not doing any operation on object, you are changing the reference itself.


                    [My Blog]
                    "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
                    "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

                    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