1

I am confused about how C# works in general when passing object instances.

This is the code I have trouble understanding:

public void foo()
{
    SomeObj obj = new SomeObj();
    obj.PropertyX = true;
    bar(obj);

    Console.Write(obj.PropertyX.toString()); //true or false?
}

public void bar(SomeObj obj)
{
    obj.PropertyX = false;
}

In the code above if the objects instance is passed by reference, I would expect the Console to print false. Is this how C# and OOP work?

Or does the instance of SomeObj in foo() preserve the state and the console prints true?

stackErr
  • 4,130
  • 3
  • 24
  • 48
  • 2
    See http://jonskeet.uk/csharp/parameters.html – Jon Skeet Jul 04 '15 at 21:15
  • Thank you, Jon Skeet! :D. Always a pleasure learning from your code and articles! – stackErr Jul 04 '15 at 21:16
  • @wazaaaap its Jon Skeet, he knew I was going to post the question even before I did. – stackErr Jul 04 '15 at 21:17
  • 1
    more like this is a question so commonly duplicated that he has a process to handle new duplicates instantly. – Claies Jul 04 '15 at 21:19
  • Is it better to delete this question then let it be marked duplicate? – stackErr Jul 04 '15 at 21:22
  • @JonSkeet, sir I have studied the link above, it refreshes concepts, one point need to ask or just need confirmation, when passing reference type with ref parameter they behave just opposite or like value type? sir Am I correct with this statement? – SSH Jul 04 '15 at 22:02
  • @SSH: That wasn't a statement, it was a question - and if you read my article carefully, you'll find the answer. – Jon Skeet Jul 04 '15 at 22:04

0 Answers0