Photon Point
Photon Point

Reputation: 808

Understanding Method Mechanism in C#?

Why is i not changed when I pass it to a method? The value of i after the method call is 0, but the method still returns 101.

class Program
{
    static void Main(string[] args)
    {
        int i = 0;
        Console.WriteLine("Before static method running i={0}", i);
        int c=   SampleClass.ExampleMethod( i);
        Console.WriteLine("i={0} - Static method return c={1}",i,c);
    }
}

class SampleClass
{
    public static int ExampleMethod(int i)
    { 
    i= 101;
    Console.WriteLine("Inside static method i={0}",i);
    return i;
    }
}

Upvotes: 0

Views: 97

Answers (2)

Cyral
Cyral

Reputation: 14153

In C#, value types (ints, doubles, etc., are passed by value, not reference. )

In order to modify the value of i, you must use the ref keyword.

class Program
{
    static void Main(string[] args)
    {
        int i = 0;
        int c=   SampleClass.ExampleMethod(ref i);
        Console.WriteLine("i={0} - c={1}",i,c);
    }
 }

class SampleClass
{
    public static int ExampleMethod(ref int i)
    {
        i = 101;
        return i;
    }
}

Usually, it is best practice not to use ref, and instead return a single value. Although in this case it is not clear on your intentions, so go with what works.

Upvotes: 4

Scott Stevens
Scott Stevens

Reputation: 380

The short answer is... I isn't really passed to your class function. A copy of I is sent. You have to explicitly tell C# to send the actual value in memory instead of a copy. You do this using the "ref" keyword. In this example... I changes...

 class Program
{
    static void Main(string[] args)
    {
        int i = 0; 
        int c = SampleClass.ExampleMethod(ref i); Console.WriteLine("i={0} - c={1}", i, c);
        Console.ReadLine();
    }

}

class SampleClass
{
    public static int ExampleMethod( ref int i)
    {
        i = 101;
        return i;
    }
}

Upvotes: 2

Related Questions