473,382 Members | 1,689 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

How do you stop a user from removing elements in a list<>?

Aimee Bailey
197 Expert 100+
In a library I am writing, I wish to stop people from removing item's from an List<> collection, is there an alternative or a way of overloading the Remove method that would stop other developers removing elements?

Aimee.
Oct 18 '10 #1

✓ answered by Christian Binder

Have you ever tried using List.AsReadOnly()-method?

This won't allow Add, Remove, Clear, ...

5 1628
Christian Binder
218 Expert 100+
Have you ever tried using List.AsReadOnly()-method?

This won't allow Add, Remove, Clear, ...
Oct 18 '10 #2
Aimee Bailey
197 Expert 100+
perfect :) just used that in the property and it does the job, thanks!

Aimee.
Oct 18 '10 #3
GaryTexmo
1,501 Expert 1GB
Just to throw alternatives around, you can also create your own class to either wrap, or inherit from a List<>. If the former, you can provide your own functionality to expose only the access methods you wish. If the latter, I think you can override the Remove method and have it do nothing, or throw an exception so the programmer knows that method isn't allowed.
Oct 18 '10 #4
Aimee Bailey
197 Expert 100+
I actually considered that, allthough it meant overriding the Add, Remove and Insert routines.
Oct 18 '10 #5
Curtis Rutland
3,256 Expert 2GB
If you need a collection that you can edit but not delete from, here's something I've used in the past:

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections;
  4. using System.Linq;
  5.  
  6. namespace Example
  7. {
  8.     class Program
  9.     {
  10.         static void Main()
  11.         {
  12.             ReadOnlyList<string> list = new ReadOnlyList<string>();
  13.             list.Add("something");
  14.             list.Add("else");
  15.             list.Add("test");
  16.             foreach (string s in list)
  17.                 Console.WriteLine(s);
  18.             var sub = list.Where(x => x.Contains("t"));
  19.             foreach (string s in sub)
  20.                 Console.WriteLine(s);
  21.             Console.ReadKey();
  22.         }
  23.     }
  24.  
  25.     public class ReadOnlyList<T> : IEnumerable<T>
  26.     {
  27.         private List<T> list;
  28.  
  29.         public ReadOnlyList()
  30.         {
  31.             list = new List<T>();
  32.         }
  33.  
  34.         public ReadOnlyList(IEnumerable<T> collection)
  35.         {
  36.             list = new List<T>(collection);
  37.         }
  38.  
  39.         public void Add(T item)
  40.         {
  41.             list.Add(item);
  42.         }
  43.  
  44.         public void AddRange(IEnumerable<T> collection)
  45.         {
  46.             list.AddRange(collection);
  47.         }
  48.  
  49.         public void Insert(int index, T item)
  50.         {
  51.             list.Insert(index, item);
  52.         }
  53.  
  54.         public void InsertRange(int index, IEnumerable<T> collection)
  55.         {
  56.             list.InsertRange(index, collection);
  57.         }
  58.  
  59.         public T this[int i]
  60.         {
  61.             get { return list[i]; }
  62.             set { list[i] = value; }
  63.         }
  64.  
  65.         public int Count { get { return list.Count; } }
  66.  
  67.         #region IEnumerable Members
  68.         public IEnumerator GetEnumerator()
  69.         {
  70.             return list.GetEnumerator();
  71.         }
  72.         #endregion
  73.  
  74.         #region IEnumerable<T> Members
  75.         IEnumerator<T> IEnumerable<T>.GetEnumerator()
  76.         {
  77.             return list.GetEnumerator();
  78.         }
  79.         #endregion
  80.     }
  81.  
  82.     public static class ExtensionMethods
  83.     {
  84.         public static ReadOnlyList<T> ToReadOnlyList<T>(this IEnumerable<T> collection)
  85.         {
  86.             return new ReadOnlyList<T>(collection);
  87.         }
  88.     }
  89. }
The basic idea is to implement IEnumerable<T>. That way, you get all the LINQ extension methods, and you can easily do foreach loops. Also, I've added an indexer, so you can treat it like an array if you want.

You can add/remove methods as needed, but you can see the pattern here.

It's a little different than inheriting from List, because with list, you still have the methods the base class has. Then, you'd have to throw exceptions or (worse) do nothing when those undesirable methods are called. In this way, you can just treat it like any other IEnumerable. System.Linq even includes a ToList extension method.

If you just wanted to be able to add, but not insert, or whatever, you could remove those methods. But if the AsReadOnly method works for you, that's a great solution too.

Also tacked on an extension method to turn other IEnumerables into a ReadOnlyList.
Oct 18 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

14
by: Dave | last post by:
Hello all, After perusing the Standard, I believe it is true to say that once you insert an element into a std::list<>, its location in memory never changes. This makes a std::list<> ideal for...
9
by: Paul | last post by:
Hi, I feel I'm going around circles on this one and would appreciate some other points of view. From a design / encapsulation point of view, what's the best practise for returning a private...
7
by: Andrew Robinson | last post by:
I have a method that needs to return either a Dictionary<k,vor a List<v> depending on input parameters and options to the method. 1. Is there any way to convert from a dictionary to a list...
56
by: Zytan | last post by:
Obviously you can't just use a simple for loop, since you may skip over elements. You could modify the loop counter each time an element is deleted. But, the loop ending condition must be...
45
by: Zytan | last post by:
This returns the following error: "Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.this' because it is not a variable" and I have no idea why! Do lists return copies...
35
by: Lee Crabtree | last post by:
This seems inconsistent and more than a little bizarre. Array.Clear sets all elements of the array to their default values (0, null, whatever), whereas List<>.Clear removes all items from the...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.