2

I am having a hard time understanding this.

If we pass variable by reference the method we are calling can change the value of the Caller's variable by changing its paramater value .

My question is

we have two variables

       int _myinteger=10;
       object _myobject=null;

here _myinteger is a value type and _myobject is reference type variable ,I want to know how can we pass these variable's by reference and how does it change's the value.? can anyone explain with an simple example.

Thank you all

4 Answers 4

4

You can pass the int by reference with the ref command, and the object is already passed by reference. More specifically, the reference to the object is passed by value.

In other words, value types are by default passed by value and reference types are by default passing their reference by value.

Consider this code:

public void ByRef(ref int i, object o)

both there are passed by reference.

UPDATE: the community wants to clarify this statement. If you were to change a value on the object that is passed it would be changed at the caller. However, if you were to build a new one (e.g. o = new Object();) with the aforementioned signature the caller would not change. If you wanted that to work as well you'd need to do this:

public void ByRef(ref int i, ref object o)
Sign up to request clarification or add additional context in comments.

14 Comments

There is no boxing of a value type when passed by reference: msdn.microsoft.com/en-us/library/vstudio/14akc2c7.aspx
@MichaelPerrenoud Also, and it will help when explaining how ref works. The reference to the object is passed by value, which is a different way of saying "reference types are passed by reference".
@Kyle My explanation of "the reference to the object is passed by value" is basically from Skeet's book and is the basis of his myth argument.
both there are passed by reference. is not true
This is the reason for Jon Skeet's explanation. o = new Object() is actually re-assigning the callee's local copy of the reference value (hence the caller's copy does not point to this new object), not working on the type it refers to. This is why ref object o does allow the caller's copy of the reference to be mutated, and hence why ref object o actually has a use. The confusion comes in when you think "reference types are passed by reference".
|
3

Use ref keyword, It helps you to pass value by reference.

The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the method is reflected in the underlying argument variable in the calling method. The value of a reference parameter is always the same as the value of the underlying argument variable.

private void DoSomething(ref int someintByRef)
{
    someintByRef = 4;
}

 int _myinteger=10;
DoSomething(ref _myinteger);
Console.WriteLine(myinteger);//Prints 4

Update: To be more clear, I'd say without the use of ref "value types" and "reference types" are passed by value only. Difference is for "value types" value(complete instance) will be copied and completely new instance is passed in case of reference types "refence of the instance" is copied and passed by value.

When we use ref, no doubt both are passed by reference

1 Comment

+1 That was a simple explanation...But why would anyone do that since it changes the variable in the calling method ..should we pass value type variable by reference ??
0

For reference types:

class User
{
    public string Name { get; set; }
    public string LastName { get; set; }
}

void ByRef(ref User user)
{
    user = new User();
}

void ByVal(User user)
{
    user = new User();
}

void Test()
{
    var user = null;
    ByVal(user);
    // user is still null
    ByRef(ref user);
    // user is new User()
}

Comments

0

There are diffrent behavior for the diffrent type of variables. if we talk about value types they are consist about the values only. the don't share memory locations. so every value type have there own values and they can play with it as they want. on the other hand refrence type variables are diffrent in nature they work with sharing mode so if i create an object then the value of this object is being shared by their users. I recomand you to have a look for below video for more clearification.

So if you pass a value type variable to a method the copy of values is being assigned to the using variable. so if you want to use the same variable. then you can have ref keywork for refranceing the value of the same object. on the other side object / refrence type variables are not needed to be ref keyword as they are already refranced by default nature.

Try below code tu understand the behavior.

 class Program
    {
        static object reftypedata = "I am Testing. ";
        static int valuetypeData = 10;

        static void Main(string[] args)
        {

            CalcValue(valuetypeData);
            CalcValuewithRef(ref valuetypeData);
            Calcobject(reftypedata);


            Console.ReadKey();

        }

        public static void CalcValue(int i)
        {
            Console.WriteLine("Value Type.....");
            Console.WriteLine("before Processing i={0}", i);
            i = 100;
            Console.WriteLine("After Processing i={0}", i);
            Console.WriteLine("After Processing valueTypeData = {0}", valuetypeData);

        }
        public static void CalcValuewithRef(ref int i)
        {
            Console.WriteLine("Value with Ref Type.....");
            Console.WriteLine("before Processing i={0}", i);
            i = 100;
            Console.WriteLine("After Processing i={0}", i);
            Console.WriteLine("After Processing valueTypeData = {0}", valuetypeData);

        }
        public static void Calcobject(object value)
        {
            Console.WriteLine("Reference Type.....");
            Console.WriteLine("before Processing value={0}", value);
            value = "Default Value Has been Changed.";
            Console.WriteLine("After Processing value={0}", value);
            Console.WriteLine("After Processing reftypedata={0}", reftypedata);


        }
    }

Output:

    Value Type.....
    before Processing i=10
    After Processing i=100
    After Processing valueTypeData = 10

 Value with Ref Type.....
    before Processing i=10
    After Processing i=100
    After Processing valueTypeData = 100

  Reference Type.....
    before Processing value=I am Testing.
    After Processing value=Default Value Has been Changed.
    After Processing reftypedata=I am Testing.

you also can reffer to this youtube video.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.