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
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