CSharp - Passing a Reference Type as Value

Introduction

The change made by CheckMe() has not reflected back inside Main().

Demo

using System;

class Program/*  ww  w .  ja  va2 s.  c  om*/
{
    static void CheckMe(string s)
    {
        s = "World";
        Console.WriteLine("Inside CheckMe(), the string value is {0}", s);//World
    }
    static void Main(string[] args)
    {
        string s = "Hello";
        Console.WriteLine("Inside Main(), Initially the  string value is {0}", s);//Hello
        CheckMe(s);
        Console.WriteLine("Inside Main(), finally the  string value is {0}", s);//Hello
    }
}

Result

Note

The string is immutable in C#.

s = "World"; is creating a new object and assigned to s.

Related Topic