Maciek
Maciek

Reputation: 19893

How do I pass a const reference in C#?

In C++, passing const references is a common practice - for instance :

#include <iostream>
using namespace std;

class X
{
  public :
    X()                              {m_x = 0; }
    X(const int & x)                 {m_x = x; }
    X(const X & other)               { *this = other; }
    X & operator = (const X & other) { m_x = other.m_x; return *this; }
    void print()                     { cout << m_x << endl; }
  private :
    int m_x;
};

void main()
{
    X x1(5);
    X x2(4);
    X x3(x2);
    x2 = x1;
    x1.print();
    x2.print();
    x3.print();
}

This very simple example illustrates how it's done - pretty much. However I've noticed that in C# this doesn't seem to be the case. Do I have to pass const references in C# ? what do I need the "ref" keyword for? Please note that I know and understand what C# reference and value types are.

Upvotes: 23

Views: 41605

Answers (4)

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

Since C# 7.2, this is possible using the in keyword.

Upvotes: 19

Martin v. L&#246;wis
Martin v. L&#246;wis

Reputation: 127447

C# doesn't have the notion of const objects (i.e. objects which you can't modify); only variables (i.e. fields) can be const or readonly - meaning that you cannot assign to them.

The ref keyword conceptually passes a reference to a variable as the parameter, i.e. the callee can modify the variable (rather than just modifying the value). This is particularly useful for the primitive types (int, bool, etc).

Upvotes: 26

Charlie
Charlie

Reputation: 10307

To answer the ref part of your question; when you pass a variable to a method, a copy of that variable is created. Using the ref keyword will pass the same instance of that variable so the method would be able to update that variable for the caller.

A lot of people seem to think this only applies to value types because reference types are just passed as a reference anyway so the ref keyword has no effect. However, this isn't true, the reference gets passed to the method in the same way as a value; it's copied and a new instance of the that reference is created. This means that the caller will see modifications to the object itself, but not to the reference. So, if you tried to set the object to null, or a new object, the caller would not see this modification if the ref keyword isn't used:

Without ref:

void UpdatePerson(Person person)
{
   // Caller would see this change
   person.Name = "Bob";
   // Caller wouldn't see this change
   person = null;
}

With ref

void UpdatePerson(ref Person person)
{
   // Caller would see this change
   person.Name = "Bob";
   // Caller would see this change
   person = null;
}

Upvotes: 29

Related Questions