0

I have problem with dictionary, i write simple code to explain that, can i achieve output 2 instead of 1?

I cannot use ref (because of TryGetValue)

static void Main(string[] args)
{
    object j = 1;
    Test(j);
    Console.WriteLine(j);
}

static void Test(object one)
{
    one = (object)2;
}

In my case i need to update dictionary row with key name with myValue

if (dictionary.TryGetValue(name, out var outObject))
{
    outObject = myValue;
}
Wojciech Rak
  • 540
  • 3
  • 17
  • That's not how you update a dictionary, that's just to get the value. Use `dictionary[name] = myValue;` to set it. – juharr May 12 '20 at 17:45
  • Although you're boxing a `1`, you're passing the reference *by value*, so the original variable isn't modified. – madreflection May 12 '20 at 17:46
  • @juharr but i dont want to double lookup for dictionary because of numbers of this operation its important for performance – Wojciech Rak May 12 '20 at 17:50
  • 4
    dictionary lookups are not expensive. Also this is only an issue if you only want to set it if the key is already there. Otherwise `dictionary[name] = myValue;` will do an update if the key is there or add it if it isn't. – juharr May 12 '20 at 17:53

1 Answers1

1

While you can pass an object to a method and modify, you cannot create a new object and have that be returned.

What you have is similar to this: Passing Objects By Reference or Value in C#

When you do this:

one = (object)2;

you are assigning a new object to one, not modifying the original instance. Since the original instance wasn't modified, you won't see the change outside that method.

Instead, what you can do is this:

static void Test(ref object one) // <---Note the "ref" key word
{
  one = (object)2;
}

This will allow you to return the object by reference.

MikeH
  • 4,242
  • 1
  • 17
  • 32
  • I said that i cannot use `ref` because i nead it to `dictionary.TryGetValue(name, out var outObject)` – Wojciech Rak May 12 '20 at 19:29
  • I see what you're getting at. Give me a minute. – MikeH May 12 '20 at 19:56
  • I think your best bet is what was proposed in comments: If you want to add the value if it doesn't exist: `dictionary[name] = myValue;`. If you don't want to add a value, do `if (dictionary.ContainsKey(name)) dictionary[name] = myValue;` – MikeH May 12 '20 at 20:00