How do I pass a const reference in C#?
- by Maciek
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.