Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

c# - What is the difference between 2 methods with ref object par and without?

I wonder what the difference is between the following methods with regards to how the object parameter is referenced:

public void DoSomething(object parameter){}

and

public void DoSomething(ref object parameter){}

Should I use ref object parameter in cases where I want to change the reference to the object not override the object in the same reference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
public void DoSomething(object parameter)
{
  parameter = new Object(); // original object from the callee would be unaffected. 
}

public void DoSomething(ref object parameter)
{
  parameter = new Object(); // original object would be a new object 
}

See the article: Parameter Passing in C# by Jon Skeet

In C#, Reference type object's address is passed by value, when the ref keyword is used then the original object can be assigned a new object or null, without ref keyword that is not possible.

Consider the following example:

class Program
{
    static void Main(string[] args)
    {
        Object obj1 = new object();
        obj1 = "Something";

        DoSomething(obj1);
        Console.WriteLine(obj1);

        DoSomethingCreateNew(ref obj1);
        Console.WriteLine(obj1);

        DoSomethingAssignNull(ref obj1);
        Console.WriteLine(obj1 == null);
        Console.ReadLine();
    }
    public static void DoSomething(object parameter)
    {
        parameter = new Object(); // original object from the callee would be unaffected. 
    }

    public static void DoSomethingCreateNew(ref object parameter)
    {
        parameter = new Object(); // original object would be a new object 
    }

    public static void DoSomethingAssignNull(ref object parameter)
    {
        parameter = null; // original object would be a null 
    }
}

Output would be:

Something
System.Object
True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...