Reference Types and Value Types

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • daniel

    Reference Types and Value Types

    This is a pretty basic-level question, but I'd really like to know, so
    thanks for any help or pointers you can provide (like what I would
    google for ;o)

    Suppose:

    <code>

    myFunc()
    {
    SomeType myType = new SomeType;
    Console.Write(m yType.MyPropert y);
    bool whatever = myOtherFunc(myT ype);
    }

    myOtherfunc(Som eType passedType)
    {
    Console.Write(m yType.ToString( ))
    return true;
    }

    </code>

    My question: since myType is a reference type, only one instance of this
    object is ever created in memory, right? The Lead Software Architect
    here (C++, no C# experience) was telling me about passing by reference--
    is this implicitly done by reference types in C#? Also, could I pass by
    value? Why would I want to?

    All these questions are asked under the auspices of least amount of
    overhead. My primary concern is good coding practices (and learning).

    Thank you,
    -daniel
  • Lateralus [MCAD]

    #2
    Re: Reference Types and Value Types

    daniel,
    To my knowledge you can't pass a "reference" type by value if you wanted
    to. It is automatically passed by reference. If you have a value type and
    you want to maintain it's value across method calls, you need to pass it by
    reference.

    example should print out 12:

    private void Test()
    {
    int index = 0;
    Test2(ref index);
    Console.Write(i ndex.ToString() );
    }

    private void Test2(ref index)
    {
    index = 12;
    }

    --
    Lateralus [MCAD]


    "daniel" <user@example.c om> wrote in message
    news:%23kBDwNTk EHA.3724@TK2MSF TNGP11.phx.gbl. ..[color=blue]
    > This is a pretty basic-level question, but I'd really like to know, so
    > thanks for any help or pointers you can provide (like what I would google
    > for ;o)
    >
    > Suppose:
    >
    > <code>
    >
    > myFunc()
    > {
    > SomeType myType = new SomeType;
    > Console.Write(m yType.MyPropert y);
    > bool whatever = myOtherFunc(myT ype);
    > }
    >
    > myOtherfunc(Som eType passedType)
    > {
    > Console.Write(m yType.ToString( ))
    > return true;
    > }
    >
    > </code>
    >
    > My question: since myType is a reference type, only one instance of this
    > object is ever created in memory, right? The Lead Software Architect here
    > (C++, no C# experience) was telling me about passing by reference--
    > is this implicitly done by reference types in C#? Also, could I pass by
    > value? Why would I want to?
    >
    > All these questions are asked under the auspices of least amount of
    > overhead. My primary concern is good coding practices (and learning).
    >
    > Thank you,
    > -daniel[/color]


    Comment

    • daniel

      #3
      Re: Reference Types and Value Types

      Ahh, thank you Lateralus for the quick reply. I have a quick follow up
      question, though:

      If a reference type is always passed by reference, then (while stupid
      and messy):

      <code>
      // with a return type this time!
      void func1()
      {
      SomeType myType = new myType();
      func2(myType);
      }
      void func2(SomeType myType)
      {
      func3(mytype);
      }
      void func3(SomeType myType)
      {
      Console.Write(m yType.ToString( ));
      }
      </code>

      will not cause a substantial amount of increased overhead at all (other
      than variables on the stack), because only one object is every created.


      Thanks,
      -daniel



      Lateralus [MCAD] wrote:
      [color=blue]
      > daniel,
      > To my knowledge you can't pass a "reference" type by value if you wanted
      > to. It is automatically passed by reference. If you have a value type and
      > you want to maintain it's value across method calls, you need to pass it by
      > reference.
      >
      > example should print out 12:
      >
      > private void Test()
      > {
      > int index = 0;
      > Test2(ref index);
      > Console.Write(i ndex.ToString() );
      > }
      >
      > private void Test2(ref index)
      > {
      > index = 12;
      > }
      >[/color]

      Comment

      • Jay B. Harlow [MVP - Outlook]

        #4
        Re: Reference Types and Value Types

        Daniel,
        For information on reference types & value types along with passing by value
        & passing by reference see:



        Hope this helps
        Jay

        "daniel" <user@example.c om> wrote in message
        news:%23kBDwNTk EHA.3724@TK2MSF TNGP11.phx.gbl. ..[color=blue]
        > This is a pretty basic-level question, but I'd really like to know, so
        > thanks for any help or pointers you can provide (like what I would google
        > for ;o)
        >
        > Suppose:
        >
        > <code>
        >
        > myFunc()
        > {
        > SomeType myType = new SomeType;
        > Console.Write(m yType.MyPropert y);
        > bool whatever = myOtherFunc(myT ype);
        > }
        >
        > myOtherfunc(Som eType passedType)
        > {
        > Console.Write(m yType.ToString( ))
        > return true;
        > }
        >
        > </code>
        >
        > My question: since myType is a reference type, only one instance of this
        > object is ever created in memory, right? The Lead Software Architect here
        > (C++, no C# experience) was telling me about passing by reference--
        > is this implicitly done by reference types in C#? Also, could I pass by
        > value? Why would I want to?
        >
        > All these questions are asked under the auspices of least amount of
        > overhead. My primary concern is good coding practices (and learning).
        >
        > Thank you,
        > -daniel[/color]


        Comment

        • Lateralus [MCAD]

          #5
          Re: Reference Types and Value Types

          daniel,
          That is correct. There is only one storage location of the object. The
          variables all just point to the same object.

          --
          Lateralus [MCAD]


          "daniel" <user@example.c om> wrote in message
          news:OfNECeTkEH A.3724@TK2MSFTN GP11.phx.gbl...[color=blue]
          > Ahh, thank you Lateralus for the quick reply. I have a quick follow up
          > question, though:
          >
          > If a reference type is always passed by reference, then (while stupid and
          > messy):
          >
          > <code>
          > // with a return type this time!
          > void func1()
          > {
          > SomeType myType = new myType();
          > func2(myType);
          > }
          > void func2(SomeType myType)
          > {
          > func3(mytype);
          > }
          > void func3(SomeType myType)
          > {
          > Console.Write(m yType.ToString( ));
          > }
          > </code>
          >
          > will not cause a substantial amount of increased overhead at all (other
          > than variables on the stack), because only one object is every created.
          >
          >
          > Thanks,
          > -daniel
          >
          >
          >
          > Lateralus [MCAD] wrote:
          >[color=green]
          >> daniel,
          >> To my knowledge you can't pass a "reference" type by value if you
          >> wanted to. It is automatically passed by reference. If you have a value
          >> type and you want to maintain it's value across method calls, you need to
          >> pass it by reference.
          >>
          >> example should print out 12:
          >>
          >> private void Test()
          >> {
          >> int index = 0;
          >> Test2(ref index);
          >> Console.Write(i ndex.ToString() );
          >> }
          >>
          >> private void Test2(ref index)
          >> {
          >> index = 12;
          >> }
          >>[/color][/color]


          Comment

          • Jeff Louie

            #6
            Re: Reference Types and Value Types

            Daniel.... By default all parameters in C# are passed by value, but you
            cannot
            pass an actual object as a parameter. You can only a pass a reference
            to an
            object as a parameter. So, by default, in C# you actually pass a
            reference by
            value as a parameter. This is very confusing to C++ coders who assume
            this
            is the equivalent of C++ pass by reference. It is not. Although the
            behavior is
            _similar_ to C++ pass by reference, it is not identical. So C++ coders
            need to
            understand first that although objects use value semantics in C++,
            objects in
            C# use reference semantics. For instance, RefVariableA= RefVariableB
            does
            not call a copy constructor in C#, it simply assigns RefVariableA to
            "point" to
            the same object "pointed" to by RefVariableB. In C#, you pass a
            reference to
            an an object by value so that a copy of the reference goes on the stack.
            The
            object is not copied. You can touch and modify the object using the
            reference
            within the method, but if you reassign the reference within the method
            there
            are no side effects outside of the method. Of course, this does not
            apply if
            you override the default behaviour and explicitly pass a parameter by
            reference. So to summarize, since objects in C++ use value semantics and
            objects in C# use reference semantics, the concept of "pass by
            reference" has
            a very different meaning in C++ and C#.

            Regards,
            Jeff[color=blue]
            >My question: since myType is a reference type, only one instance of[/color]
            this
            object is ever created in memory, right? The Lead Software Architect
            here (C++, no C# experience) was telling me about passing by reference--
            is this implicitly done by reference types in C#? Also, could I pass by
            value?<

            *** Sent via Developersdex http://www.developersdex.com ***
            Don't just participate in USENET...get rewarded for it!

            Comment

            • daniel

              #7
              Re: Reference Types and Value Types

              Thank you Lateralus, Jay and Jeff.

              Comment

              • Jon Skeet [C# MVP]

                #8
                Re: Reference Types and Value Types

                <"Lateralus [MCAD]" <dnorm252_at_ya hoo.com>> wrote:[color=blue]
                > To my knowledge you can't pass a "reference" type by value if you wanted
                > to. It is automatically passed by reference.[/color]

                No. The reference is passed by value, which is quite different.

                See http://www.pobox.com/~skeet/csharp/parameters.html

                --
                Jon Skeet - <skeet@pobox.co m>
                Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                If replying to the group, please do not mail me too

                Comment

                • Patty O'Dors

                  #9
                  RE: Reference Types and Value Types

                  You can't pass by value in C#, not unless the type is a value type, like
                  something that is declared 'struct' rather than 'class', or a basic variable
                  like int, byte etc.
                  There's no reason why you'd want to, if you did, then that'd be tantamount
                  to trying to do the garbage collector's work for it, and it was designed to
                  be global and operate off its own bat.
                  So just don't bother about the memory - just make it as OO as possible.

                  "daniel" wrote:
                  [color=blue]
                  > This is a pretty basic-level question, but I'd really like to know, so
                  > thanks for any help or pointers you can provide (like what I would
                  > google for ;o)
                  >
                  > Suppose:
                  >
                  > <code>
                  >
                  > myFunc()
                  > {
                  > SomeType myType = new SomeType;
                  > Console.Write(m yType.MyPropert y);
                  > bool whatever = myOtherFunc(myT ype);
                  > }
                  >
                  > myOtherfunc(Som eType passedType)
                  > {
                  > Console.Write(m yType.ToString( ))
                  > return true;
                  > }
                  >
                  > </code>
                  >
                  > My question: since myType is a reference type, only one instance of this
                  > object is ever created in memory, right? The Lead Software Architect
                  > here (C++, no C# experience) was telling me about passing by reference--
                  > is this implicitly done by reference types in C#? Also, could I pass by
                  > value? Why would I want to?
                  >
                  > All these questions are asked under the auspices of least amount of
                  > overhead. My primary concern is good coding practices (and learning).
                  >
                  > Thank you,
                  > -daniel
                  >[/color]

                  Comment

                  • Jon Skeet [C# MVP]

                    #10
                    RE: Reference Types and Value Types

                    Patty O'Dors <PattyODors@dis cussions.micros oft.com> wrote:[color=blue]
                    > You can't pass by value in C#, not unless the type is a value type, like
                    > something that is declared 'struct' rather than 'class', or a basic variable
                    > like int, byte etc.[/color]

                    Not true. Everything is passed by value by default - whether the value
                    is a struct or a reference. You can't pass an actual *object* either by
                    reference or by value.

                    --
                    Jon Skeet - <skeet@pobox.co m>
                    Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                    If replying to the group, please do not mail me too

                    Comment

                    • Champika Nirosh

                      #11
                      Re: Reference Types and Value Types

                      How about assigning a deep clone of the reference type object to a new
                      object of same type.. at the method..

                      Nirosh.

                      "Lateralus [MCAD]" <dnorm252_at_ya hoo.com> wrote in message
                      news:eLFDzjVkEH A.3968@TK2MSFTN GP11.phx.gbl...[color=blue]
                      > daniel,
                      > That is correct. There is only one storage location of the object. The
                      > variables all just point to the same object.
                      >
                      > --
                      > Lateralus [MCAD]
                      >
                      >
                      > "daniel" <user@example.c om> wrote in message
                      > news:OfNECeTkEH A.3724@TK2MSFTN GP11.phx.gbl...[color=green]
                      > > Ahh, thank you Lateralus for the quick reply. I have a quick follow up
                      > > question, though:
                      > >
                      > > If a reference type is always passed by reference, then (while stupid[/color][/color]
                      and[color=blue][color=green]
                      > > messy):
                      > >
                      > > <code>
                      > > // with a return type this time!
                      > > void func1()
                      > > {
                      > > SomeType myType = new myType();
                      > > func2(myType);
                      > > }
                      > > void func2(SomeType myType)
                      > > {
                      > > func3(mytype);
                      > > }
                      > > void func3(SomeType myType)
                      > > {
                      > > Console.Write(m yType.ToString( ));
                      > > }
                      > > </code>
                      > >
                      > > will not cause a substantial amount of increased overhead at all (other
                      > > than variables on the stack), because only one object is every created.
                      > >
                      > >
                      > > Thanks,
                      > > -daniel
                      > >
                      > >
                      > >
                      > > Lateralus [MCAD] wrote:
                      > >[color=darkred]
                      > >> daniel,
                      > >> To my knowledge you can't pass a "reference" type by value if you
                      > >> wanted to. It is automatically passed by reference. If you have a value
                      > >> type and you want to maintain it's value across method calls, you need[/color][/color][/color]
                      to[color=blue][color=green][color=darkred]
                      > >> pass it by reference.
                      > >>
                      > >> example should print out 12:
                      > >>
                      > >> private void Test()
                      > >> {
                      > >> int index = 0;
                      > >> Test2(ref index);
                      > >> Console.Write(i ndex.ToString() );
                      > >> }
                      > >>
                      > >> private void Test2(ref index)
                      > >> {
                      > >> index = 12;
                      > >> }
                      > >>[/color][/color]
                      >
                      >[/color]


                      Comment

                      • Champika Nirosh

                        #12
                        Re: Reference Types and Value Types


                        "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message
                        news:MPG.1ba27a 49964d884998b34 0@msnews.micros oft.com...[color=blue]
                        > Patty O'Dors <PattyODors@dis cussions.micros oft.com> wrote:[color=green]
                        > > You can't pass by value in C#, not unless the type is a value type, like
                        > > something that is declared 'struct' rather than 'class', or a basic[/color][/color]
                        variable[color=blue][color=green]
                        > > like int, byte etc.[/color]
                        >
                        > Not true. Everything is passed by value by default - whether the value
                        > is a struct or a reference. You can't pass an actual *object* either by
                        > reference or by value.[/color]

                        "Everything " are u sure....?????
                        [color=blue]
                        > --
                        > Jon Skeet - <skeet@pobox.co m>
                        > http://www.pobox.com/~skeet
                        > If replying to the group, please do not mail me too[/color]


                        Comment

                        • Jon Skeet [C# MVP]

                          #13
                          Re: Reference Types and Value Types

                          Champika Nirosh <test@test.lk > wrote:[color=blue][color=green]
                          > > Not true. Everything is passed by value by default - whether the value
                          > > is a struct or a reference. You can't pass an actual *object* either by
                          > > reference or by value.[/color]
                          >
                          > "Everything " are u sure....?????[/color]

                          Absolutely. See http://www.pobox.com/~skeet/csharp/parameters.html

                          --
                          Jon Skeet - <skeet@pobox.co m>
                          Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                          If replying to the group, please do not mail me too

                          Comment

                          • Champika Nirosh

                            #14
                            Re: Reference Types and Value Types

                            Hi Jon,

                            I think it is not a fair comment...

                            "Everything is passed by value by default"

                            Instead.. What you would said is.. reference of the reference type variable
                            is passed by its' value.. or object references are passed by value by
                            default..

                            You statement is misleading... One might take it as .. object also passed by
                            its' value.. what happen actaully is since reference type cannot passed by
                            value even though you try they passes their reference..

                            Nirosh.

                            "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message
                            news:MPG.1bd441 4677f9299a98b64 c@msnews.micros oft.com...[color=blue]
                            > Champika Nirosh <test@test.lk > wrote:[color=green][color=darkred]
                            > > > Not true. Everything is passed by value by default - whether the value
                            > > > is a struct or a reference. You can't pass an actual *object* either[/color][/color][/color]
                            by[color=blue][color=green][color=darkred]
                            > > > reference or by value.[/color]
                            > >
                            > > "Everything " are u sure....?????[/color]
                            >
                            > Absolutely. See http://www.pobox.com/~skeet/csharp/parameters.html
                            >
                            > --
                            > Jon Skeet - <skeet@pobox.co m>
                            > http://www.pobox.com/~skeet
                            > If replying to the group, please do not mail me too[/color]


                            Comment

                            • Jon Skeet [C# MVP]

                              #15
                              Re: Reference Types and Value Types

                              Champika Nirosh <test@test.lk > wrote:[color=blue]
                              > I think it is not a fair comment...
                              >
                              > "Everything is passed by value by default"[/color]

                              It's a true comment. The only things which can be passed are value
                              types and references. Both of those are passed by value by default.
                              [color=blue]
                              > Instead.. What you would said is.. reference of the reference type variable
                              > is passed by its' value.. or object references are passed by value by
                              > default..[/color]

                              But that's all that *can* be passed. Note that it's not the reference
                              of the reference type variable - it's the *value* of a reference type
                              variable, and that value is a reference.
                              [color=blue]
                              > You statement is misleading... One might take it as .. object also passed by
                              > its' value.. what happen actaully is since reference type cannot passed by
                              > value even though you try they passes their reference..[/color]

                              If that's all I'd said, you'd be right. However, look at what I *did*
                              say:

                              <quote>
                              Not true. Everything is passed by value by default - whether the value
                              is a struct or a reference. You can't pass an actual *object* either by
                              reference or by value.
                              </quote>

                              Now, how can *that* be taken as "object also passed by its value"?

                              --
                              Jon Skeet - <skeet@pobox.co m>
                              Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                              If replying to the group, please do not mail me too

                              Comment

                              Working...