Question about passing reference type to a method

  • Thread starter Thread starter Alex
  • Start date Start date
A

Alex

When I pass a reference to a method by value, the reference argument to the
method is copied but still points to the original object, and that method
can modify the object. Can I apply const keyword to the argument to prevent
this?

f.e.,

instead of:

void Method(mytype obj)
{
// can modify obj
}

do:

void Method(const mytype obj)
{
// can't modify obj
}
 
No, you can't. What's your use case here? Why are you
wanting to do this?

Richard
 
Hi Alex,

No, you can't this have been subject of debate before, if you don't
want your object to be change and you know for sure or donot know if
the calling method will modify it you will need to clone it before.

Thank you, I hope that the C# designers take heed and add const parameters!
 
Back
Top