?
Solved

How to make sure a parm to a method cannot be changed.

Posted on 2011-02-27
7
Medium Priority
?
252 Views
Last Modified: 2012-05-11
In c++ the word “const” can be used in parameters so that the compiler will error if code is written that will try to change the parm.  Users of this method do not have to worry about its contents being changed.  How do I do this in c#, even when the term “ref” is not used the contents of the parameter can be changed.

The difference between the two example lines of code is the c++ version has the key word "const".  It is this behavior I am trying to obtain in c#.

C#
private StringCollection GetHeaderQuerySet(ref Data4 dataFile, Hashtable hashList)
{
hashList.Add(“newKey”, “newValue”); //This changes the list even though the list is not passed by reference.  Any method calling this method takes a chance the hashlist is changed.

C++
private CStringArray GetHeaderQuerySet(Data4 &dataFile, const HastTable &hashList)
{
hashList.Add(“newKey”, “newValue”); //Compiler flags this as an error

Thank you for your time and consideration.
0
Comment
Question by:wilfordrocks
7 Comments
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 288 total points
ID: 34992929
I don't think there is such a thing in C#.  =\
*I could be wrong though...

One way would be to wrap the HashTable in a class that only allows you to query the hashtable.
Otherwise you'd have to make a copy of the contents in the hashtable and pass that in so that changes would be in the copy and no the original.
0
 
LVL 30

Accepted Solution

by:
anarki_jimbel earned 288 total points
ID: 34992954
You cannot make an object constant.

And, as a matter of fact, you pass the list by reference. Or, in other words, you pass a REFERENCE to the list, kinda it's address, not a list itself. Really, ref make sense mostly for value types only, like integer, date, point etc.
This is a good article that explains how it works:
http://www.yoda.arachsys.com/csharp/parameters.html

Not even sure what to advice. Pass a copy of a collection to the method call if you want to be safe from any collection modification and somehow have no control on what this method is doing.
0
 
LVL 10

Assisted Solution

by:eguilherme
eguilherme earned 284 total points
ID: 34993031
your best option i think would be to mkae another class that implements hashtable and in there you could make a method that would allow or not the adding /editing of new items
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 27

Assisted Solution

by:nmarun
nmarun earned 856 total points
ID: 34994216
How about creating a second class that has a property with only a getter:

http://www.c-sharpcorner.com/UploadFile/bulentozkir/PassingConstInCS11082005014622AM/PassingConstInCS.aspx

Arun
0
 
LVL 27

Assisted Solution

by:nmarun
nmarun earned 856 total points
ID: 34994268
Sorry the above will not work in your case. Try using an IList for this and you can create a ReadOnlyCollection using the AsReadOnly() extension method.

The MSDN article is here:
http://msdn.microsoft.com/en-us/library/e78dcd75.aspx

The code is the exact same as in the article, but I've tried to modify the collection and this will through an error.

Arun
public static void ReadonlyDictionary()
{
    List<string> dinosaurs = new List<string>(4);

    Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

    dinosaurs.Add("Tyrannosaurus");
    dinosaurs.Add("Amargasaurus");
    dinosaurs.Add("Mamenchisaurus");
    dinosaurs.Add("Deinonychus");

    Console.WriteLine();
    foreach (string s in dinosaurs)
    {
        Console.WriteLine(s);
    }

    Console.WriteLine("\nIList<string> roDinosaurs = dinosaurs.AsReadOnly()");
    IList<string> roDinosaurs = dinosaurs.AsReadOnly();

    Console.WriteLine("\nElements in the read-only IList:");
    foreach (string dinosaur in roDinosaurs)
    {
        Console.WriteLine(dinosaur);
    }

    Console.WriteLine("\ndinosaurs[2] = \"Coelophysis\"");
    dinosaurs[2] = "Coelophysis";

    roDinosaurs[2] = "Coelophysis";
    Console.WriteLine("\nElements in the read-only IList:");
    foreach (string dinosaur in roDinosaurs)
    {
        Console.WriteLine(dinosaur);
    }
}

Open in new window

0
 
LVL 20

Assisted Solution

by:informaniac
informaniac earned 284 total points
ID: 34994567
Inside the method do, hashList = new HashTable();hashList.Add...
0
 
LVL 27

Assisted Solution

by:nmarun
nmarun earned 856 total points
ID: 34994664
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question