?
Solved

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

Posted on 2011-02-27
7
Medium Priority
?
249 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

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 article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Suggested Courses
Course of the Month14 days, 18 hours left to enroll

770 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