Const Object Reference in C# function

  • Thread starter Thread starter Shreyas Ranade
  • Start date Start date
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#.
 
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.
 
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.
 
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
 
Back
Top