4

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 .

6
  • No. There is not. This has come up before and I remember seeing a good response by Eric Lippert. Commented Oct 21, 2011 at 3:55
  • 3
    Can you explain why you would want something like that? Value types cannot do that. Commented Oct 21, 2011 at 3:56
  • stackoverflow.com/questions/1420186/… Commented Oct 21, 2011 at 4:02
  • 1
    stackoverflow.com/questions/3284767/… Commented Oct 21, 2011 at 4:08
  • 1
    @Bala R It has nothing to do with value vs. reference types. Question is about creating a reference [to a variable] (as is possible in C++), not about mutability [of objects]... granted there are generally "better approaches" to this problem. Commented Oct 21, 2011 at 4:15

6 Answers 6

10

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Here's an example, being able to make x to be i or j outside of the loop would've been much nicer. i.imgur.com/W12AMCN.png
Looking for the exact same feature I found this question (among many others alike). I have a situation which I consider very ordinary and I can't see a decent workaround to using a reference. What I want does not involve pointers, memory addresses or other "complicated" features of C++. I need a simple ("blind") reference (alias) more in the direction of #define from C++. I'm not either interested in passing/returning ref to/from functions, so there would be no stack related issues either. Take my situation:
Situation: I have a few int variables and at the press of a key (in a loop) I "assign" one to be the working variable from now on. Now all the work to follow (many functions) have to be on that particular variable (i.e. press another key to read/write to it). I can't see how to avoid unnecessary/overhead code. C++ reference is absolutely perfect. Besides IMHO, just as passing by value for ref-types is allowed, the opposite should be as well.
@mireazma: So then why not make a delegate which writes the variable? That then is your thing which represents access to the variable, and moreover, the lifetime of the variable is extended to the lifetime of the delegate instance.
See also Proposal: Ref Returns and Locals . Note that it was closed as implemented on September 19th, and shows up on learn.microsoft.com/en-us/dotnet/articles/csharp/csharp-7 . So, this feature may be available in C# 7.
|
4

'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;

2 Comments

Note that this solution may not be practical if x was originally a field in a class. In such a situation, you can instead use this code provided by Eric Lippert in response to a similar question.
Note: x and y could be local variables for reference types, and the same truth applies. Reassigning y does not affect x. The bit about value types is irrelevant.
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
}

Comments

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)

Comments

0

The only way to do this is to use "unsafe" code, and actually use pointers. Pointers cannot exist outside of unsafe code blocks in C#. You should then be able to use pointers the same way you do in C/C++

Check out this page for how to use "unsafe" code blocks.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.