for example:
int x = 1;
int y = x;
y = 3;
Debug.WriteLine(x.ToString());
Is it any reference operator instead of "=" on line:3, to make the x equal to 3 , if i assign y =3 .
for example:
int x = 1;
int y = x;
y = 3;
Debug.WriteLine(x.ToString());
Is it any reference operator instead of "=" on line:3, to make the x equal to 3 , if i assign y =3 .
I once wrote a prototype of a version of C# that had that feature; you could say:
int x = 123;
ref int y = ref x;
and now x and y would be aliases for the same variable.
We decided to not add the feature to the language; if you have a really awesome usage case I'd love to hear it.
You're not the first person to ask about this feature; see Can I use a reference inside a C# function like C++? for more details.
UPDATE: The feature will likely be in C# 7.
'int' is a value type and so copies the value on assignment, as you have discovered.
You could use pointers in the traditional C/C++ sense by using an 'unsafe' block but then the pointers are only usable inside that block which limits its use. If instead you want to access the value outside of an 'unsafe' block then you need to convert to using a reference instead.
Something like this...
var x = new Tuple<int>(1);
var y = x;
y.Item1 = 3;
This is not exactly what you're asking, but I thought it might be helpful. If you want a pointer alias inside a function, you can use the ref
keyword like such:
public static void RefExample(ref int y)
{
y = 3;
}
main()
{
int x = 5;
RefExample(ref x);
Console.WriteLine(x); // prints 3
}
You can use pointers like in C
int x = 1;
unsafe
{
int* y = &x;
*y = 3;
}
Debug.WriteLine(x.ToString());
(Note you have to compile with the unsafe flag)
I wanted to comment Eric Lippert's answer, but new users cannot comments posts. So, I think I have such usage.
Take a look at this code:
private void SetGridColumns(ref RegistryKey targetKey, List<ColInfo> cols)
{
string targetKeyName = Path.GetFileName(targetKey.Name);
m_grids.DeleteSubKeyTree(targetKeyName, false);
targetKey.Close();
targetKey = m_grids.CreateSubKey(targetKeyName);
//... }
public void SetColumns(List<ColInfo> cols, bool youth)
{
RegistryKey key = youth ? m_youthGrid : m_mainGrid;
SetGridColumns(ref key, cols);
}
It should work like that: In SetColumns I call SetGridColumns with key depending on "youth" param. I would like my key to be first deleted and then recreated. m_mainGrid is of course member of a class. In this case, key is indeed deleted and recreated. But recreated is only "targetKey" in SetGridColumns, not my m_mainGrid.
So, the only thing I can do here is to make usage of pointers which is not preferred way in C#. If I could only do:
ref RegistryKey key = youth ? m_youthGrid : m_mainGrid;
everything should work fine.