Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I prevent users from modify the parameters in C#

Tags:

performance

c#

I'm coding in C# for a group of people, I'm designing the signature of the methods to be coded and I need a way to ensure that people won't modify some parameters they will receive. They receive big structures so they are sent by reference, but I want they to consume the data without modifying the original values. But since the structures are big we don't want to make copies of them.

We can assume they don't want to change the data and we only need to protect them from making mistakes.

What solutions does C# offer?

Here's and example

class MyDataBlok {
    List<double> samples;
    int someParams;
    double lots of other params
    }

class MySetOfDataBlock
{
    List<MyDataBlock> DataSet;
    bool SomeParam;
    Double lots of other params;
}

class MethodsToBeCoded
{
    ProcessSetOfData( /*some tag defining data as protected*/ MySetOfDataBlock data)
    {
         //Here I want code that uses data without modifying data
         // nor the content on any data.DataSet[i]
    }
}
like image 576
javirs Avatar asked Jan 26 '17 09:01

javirs


1 Answers

The pessimistic answer is None. If the want to change the data, they will. There is nothing you can do except making copies.


The optimistic answer assumes they don't want to change the data and you only need to protect them from making mistakes. Now that is possible:

Don't give them any setters. You did not say what your data looks like so I can give you only a vague description:

Do not expose the setters. Give them interfaces to your data classes that do not have setters, return collections as IEnumerable<> instead of the modifiable instance they are and so on. Make sure that through the interface they get to your data, your data cannot be modified.

like image 101
nvoigt Avatar answered Oct 22 '22 16:10

nvoigt