Solved

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

Posted on 2011-02-27
7
243 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 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 72 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 29

Accepted Solution

by:
anarki_jimbel earned 72 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 71 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 27

Assisted Solution

by:nmarun
nmarun earned 214 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 214 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 71 total points
ID: 34994567
Inside the method do, hashList = new HashTable();hashList.Add...
0
 
LVL 27

Assisted Solution

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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
creating a flowchart from an algorithm 5 30
Image(7) 1 53
Error on Add method 1 38
free scanner TWAIN can be operated with a Web application 9 40
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

895 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now