Passing arguments by value - CSharp Custom Type

CSharp examples for Custom Type:Method Parameter

Introduction

By default, arguments in C# are passed by value , which is by far the most common case.

A copy of the value is created when passed to the method:

Demo Code

using System;// w ww.ja  v  a  2s  .c  o m
class Test
{
   static void Foo (int p)
   {
      p = p + 1;                // Increment p by 1
      Console.WriteLine (p);    // Write p to screen
   }
   static void Main()
   {
      int x = 8;
      Foo (x);                  // Make a copy of x
      Console.WriteLine (x);    // x will still be 8
   }
}

Result

Passing a reference-type argument by value copies the reference, but not the object.

Demo Code

using System;/*from ww w  .j  a v a  2s. co  m*/
using System.Text;

class Test
{
    static void Foo(StringBuilder fooSB)
    {
        fooSB.Append("test");
        fooSB = null;
    }
    static void Main()
    {
        StringBuilder sb = new StringBuilder();
        Foo(sb);
        Console.WriteLine(sb.ToString());    // test
    }
}

Result


Related Tutorials