read only (const) parameters

G

Guest

Hey, all.

I need some help to figure out what is the correct way in C# to pass
parameters by reference but keep them constant.

In C++ it's recommended to pass all of your objects by reference in order to
avoid copying of those objects and the same time make a parameter a const to
prevent the function from changing the parameter, i.e.

instead of

void Foo(Class1 obj)
{
}

use

void Foo(const Class1& obj)
{
}


I couldn't find any specifiiers in C# to make a parameter to a function a
read-only. The only possible solution I have is to derive a class from a
read-only interface and to pass an interface to a function.

For instanse:

class IReadOnlyClass1
{
int A{get;}
}

class Class1 : IReadOnlyClass1
{
public int A {get{...} set {...}
}

so, now I can create my function
void Foo(IReadOnlyClass1 obj)
{
}

In C++ any object can be passed as a const reference. To achieve the same in
C#, I would be forced to have every class to be derived from a read-only
interface.

Does it seem like an overkill? Is there a better way (a C# built-in
mechanism) for achieving the same goal?

Thanks for your input.

Sincerely,
Vic
 
J

Jeff Louie

Vic... That functionality is not available in C#. You can pass a copy.
You can
wrap the object in a read only adapter. OR you can pass references to
immutable objects/structures. The use of immutable objects goes against
tradition, but has proponents:

Item 13: Favor immutability Effective Java

Immutabale objects are simple
Immutable objects are inherently thread safe
Immutable objects can be shared freely

"Classes should be immutable unless there's a very good reason to make
them mutable." Joshua Bloch

Regards,
Jeff
I need some help to figure out what is the correct way in C# to pass
parameters by reference but keep them constant.<


*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top