Const Object Reference in C# function

S

Shreyas Ranade

I want to pass an Object Reference to a C# function, but also I want to make
sure that the calling function should not change it's value.
The C++ Code Like

MyClass cls;
Fun1(cls)

void Fun1(const MyClass & cls)
{
int a = cls.m_No;
}


I want to write same code in C#. How should I write because
you can not send Cont Object Reference to a function in C#.
 
G

Greg Ewing [MVP]

Shreyas, there isn't a straighforward way to do this. One work around would
be only providing a getter like Morten suggested. You could also use a
Field instead of a property and apply the readonly attribute to the field.
Not sure which will work with your exact scenario.
 
D

Darren Oakey

My favorite way is to have an interface for every class which is
changeable -

ie
interface ConstMyClass
{
int number {get;}
string value {get;}
ConstMyClass CombineWith( ConstMyClass);
...
}

then have your class implement that
ie
class MyClass : ConstMyClass
{
....
}

then most of the places you use it, you can define
void Fun1( ConstMyClass x )
{
}

and be 100% guaranteed that your object isn't going to be manipulated.
 
J

Jon Skeet

Darren Oakey said:
My favorite way is to have an interface for every class which is
changeable -

ie
interface ConstMyClass
{
int number {get;}
string value {get;}
ConstMyClass CombineWith( ConstMyClass);
...
}

then have your class implement that
ie
class MyClass : ConstMyClass
{
...
}

then most of the places you use it, you can define
void Fun1( ConstMyClass x )
{
}

and be 100% guaranteed that your object isn't going to be manipulated.

Unfortunately it doesn't, actually - because the client can always
check whether or not the instance is *actually* an instance of MyClass,
cast it, and then manipulate it.

What you *can* do is have a wrapper which *contains* an instance of
MyClass, and delegates read access to it, eg:

class ConstMyClass
{
MyClass target;

public ConstMyClass (MyClass target)
{
this.target = target;
}

public int Number
{
get { return target.Number; }
}
}

etc
 

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