开发者

Return By Reference in c#? [duplicate]

This question already has answers here: 开发者_StackOverflow Is it Possible to Return a Reference to a Variable in C#? [duplicate] (5 answers) Closed 9 years ago.

How to return by reference using function.Please provide me with complete funcion definition which returns by reference in c#.Is there any other way to pass reference? Please help.


This is a method that returns an object reference by value:

string Foo()
{
    return "Hello";
}

string f = Foo();
//  f == "Hello"

You can't return anything by reference, but you can pass a variable by reference as an argument:

void Bar(ref string s)
{
    s = "Hello";
}

string f = null;
Bar(ref f);
//  f == "Hello"

See: Parameter passing in C#


With the risk of sounding mean, you should read the C# reference :)

C# divides things into reference types and value types. Reference types are as you can imagine, being passed by reference. This means a reference to the object is passed.

Here is a contrived example of return by reference:

class MyClass // <- Reference type.
{
   private MyClass _child = new MyClass();

   public MyClass GetChild()
   {
      return _child;
   }
}

Value types are passed by value; although I imagine under the hood something else could be going on. This is not important to you though, only the behaviour is important.

Example of value types: int, char, Color...

You create a reference type through class, and a value type through struct.


Returning a reference is a C++ term. An example that demonstrates the syntax:

class Array {                  // This is C++ code
 public:
   int size() const;
   float& operator[] (int index);
   ...
 };

 int main()
 {
   Array a;
   for (int i = 0; i < a.size(); ++i)
     a[i] = 7;    // This line invokes Array::operator[](int)
   ...
 } 

C# doesn't have this capability, it is quite incompatible with the notion of a garbage collector. C++ implements this under the hood by actually returning a pointer. This falls flat when the garbage collector moves the underlying internal array, the pointer becomes invalid.

It is not much of a problem because variables of an object are already true references in managed code, much like the C++ notion of a reference. But not value types, they are copied. You'd use an indexer in this specific example:

class Array<T> {            // This is C# code
    private T[] storage;
    public T this[int index] {
        get { return storage[index]; }
        set { storage[index] = value; }
    }
    // etc...        
}


If you return a reference type from a function you have the object by reference. You may want to read up on refence and value types and passing parameter (by ref and out). See CLR via C#

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜