Solved

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

Posted on 2011-02-27
7
242 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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

747 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

13 Experts available now in Live!

Get 1:1 Help Now