473,385 Members | 1,343 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,385 software developers and data experts.

How to create a generic readonly collection?

I know I can use ArrayList.ReadOnly() to create a readonly version of it,
but how can I achive a similar thing with a generic collection of .NET 2.0?
Nov 17 '05 #1
5 3066


cody wrote:
I know I can use ArrayList.ReadOnly() to create a readonly version of it,
but how can I achive a similar thing with a generic collection of .NET 2.0?


Implement a proxy for the relevant collection, which throw's on mutation.

Here is an example on the .NET1.1 IDictionary, I haven't changed to
..NET2 yet -- you should be able to write one for IDictionary<> in .NET2
yourself.

using System.Collections;

class Immutable: Exception
{ public Immutable(): base("Attempt to change immutable object") {} }

/// <summary>
/// Provide immutable access to a dictionary.
/// </summary>
/// <remarks>
/// In JAVA, iterators, as well as the key- and value- parts, of a
dictionary
/// (called Map) allows mutation, so in JAVA a much more elaborate proxying
/// is required.
/// </remarks>
class ImmutableIDictionary: IDictionary
{
protected readonly IDictionary proxied;
public ImmutableIDictionary(IDictionary proxied) {
if ( proxied == null )
throw new ArgumentException(
"Cannot proxy uninstantiated IDictionary", "proxied");
this.proxied = proxied;
}
#region IDictionary Members
public bool IsReadOnly { get { return true; } }
public IDictionaryEnumerator GetEnumerator()
{ return proxied.GetEnumerator(); }
public object this[object key]
{ get { return proxied[key]; } set { throw new Immutable(); } }
public void Remove(object key) { throw new Immutable(); }
public bool Contains(object key) { return proxied.Contains(key); }
public void Clear() { throw new Immutable(); }
public ICollection Values { get { return proxied.Values; } }
public void Add(object key, object value) { throw new Immutable(); }
public ICollection Keys { get { return proxied.Keys; } }
public bool IsFixedSize { get { return true; } }
#endregion

#region ICollection Members
public bool IsSynchronized { get { return proxied.IsSynchronized; } }
public int Count { get { return proxied.Count; } }
public void CopyTo(Array array, int index) { proxied.CopyTo(array,
index); }
public object SyncRoot { get { return proxied.SyncRoot; } }
#endregion

#region IEnumerable Members
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
IEnumerable e = proxied;
return e.GetEnumerator();
}
#endregion
}

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #2
Thanks for the answer.

So that means there is no predefined method for getting a readonly List<> in
..NET 2.0?

This is very bad. Since .NET lacks the const modifier like in C++ there
should at least be a simple solution for that without having to write
readonly wrappers for all collection classes all the time by myself :(

"Helge Jensen" <he**********@slog.dk> schrieb im Newsbeitrag
news:#l**************@TK2MSFTNGP12.phx.gbl...


cody wrote:
I know I can use ArrayList.ReadOnly() to create a readonly version of it, but how can I achive a similar thing with a generic collection of .NET
2.0?
Implement a proxy for the relevant collection, which throw's on mutation.

Here is an example on the .NET1.1 IDictionary, I haven't changed to
.NET2 yet -- you should be able to write one for IDictionary<> in .NET2
yourself.

using System.Collections;

class Immutable: Exception
{ public Immutable(): base("Attempt to change immutable object") {} }

/// <summary>
/// Provide immutable access to a dictionary.
/// </summary>
/// <remarks>
/// In JAVA, iterators, as well as the key- and value- parts, of a
dictionary
/// (called Map) allows mutation, so in JAVA a much more elaborate proxying /// is required.
/// </remarks>
class ImmutableIDictionary: IDictionary
{
protected readonly IDictionary proxied;
public ImmutableIDictionary(IDictionary proxied) {
if ( proxied == null )
throw new ArgumentException(
"Cannot proxy uninstantiated IDictionary", "proxied");
this.proxied = proxied;
}
#region IDictionary Members
public bool IsReadOnly { get { return true; } }
public IDictionaryEnumerator GetEnumerator()
{ return proxied.GetEnumerator(); }
public object this[object key]
{ get { return proxied[key]; } set { throw new Immutable(); } }
public void Remove(object key) { throw new Immutable(); }
public bool Contains(object key) { return proxied.Contains(key); }
public void Clear() { throw new Immutable(); }
public ICollection Values { get { return proxied.Values; } }
public void Add(object key, object value) { throw new Immutable(); }
public ICollection Keys { get { return proxied.Keys; } }
public bool IsFixedSize { get { return true; } }
#endregion

#region ICollection Members
public bool IsSynchronized { get { return proxied.IsSynchronized; } }
public int Count { get { return proxied.Count; } }
public void CopyTo(Array array, int index) { proxied.CopyTo(array,
index); }
public object SyncRoot { get { return proxied.SyncRoot; } }
#endregion

#region IEnumerable Members
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
IEnumerable e = proxied;
return e.GetEnumerator();
}
#endregion
}

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-

Nov 17 '05 #3


Matthias Schack wrote:
Thanks for the answer.

So that means there is no predefined method for getting a readonly List<> in
.NET 2.0?
I am not qualified to answer that, since I haven't used 2.0 yet, *but*
since .NET1.1 doesn't have it, and I haven't read about it being
introduced in .NET2, and since you asked (I suppose you've looked in the
docs), there quite possibly aren't any.
This is very bad. Since .NET lacks the const modifier like in C++ there
should at least be a simple solution for that without having to write
readonly wrappers for all collection classes all the time by myself :(


Aaaah, lots of things are far worse, besides const comes with just about
as many problems as it solves (hence the discussion about whether it's
good or bad).

Really, ICollection does not provide mutation, that leaves IList and
IDictionary from .NET1.1 and (to my poor knowledge) IList<>,
IDictionary<> and ISet<> from .NET2. All in all 5 classes.

Just be glad you're not in JAVA, where writing a readonly proxy is much
more complicated.

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #4
List.AsReadOnly retuns a read-only wrapper arround the current List.
Willy.

"Matthias Schack" <Sc***********@gmx.de> wrote in message
news:uJ*************@TK2MSFTNGP10.phx.gbl...
Thanks for the answer.

So that means there is no predefined method for getting a readonly List<>
in
.NET 2.0?

This is very bad. Since .NET lacks the const modifier like in C++ there
should at least be a simple solution for that without having to write
readonly wrappers for all collection classes all the time by myself :(

"Helge Jensen" <he**********@slog.dk> schrieb im Newsbeitrag
news:#l**************@TK2MSFTNGP12.phx.gbl...


cody wrote:
> I know I can use ArrayList.ReadOnly() to create a readonly version of it, > but how can I achive a similar thing with a generic collection of .NET

2.0?

Implement a proxy for the relevant collection, which throw's on mutation.

Here is an example on the .NET1.1 IDictionary, I haven't changed to
.NET2 yet -- you should be able to write one for IDictionary<> in .NET2
yourself.

using System.Collections;

class Immutable: Exception
{ public Immutable(): base("Attempt to change immutable object") {} }

/// <summary>
/// Provide immutable access to a dictionary.
/// </summary>
/// <remarks>
/// In JAVA, iterators, as well as the key- and value- parts, of a
dictionary
/// (called Map) allows mutation, so in JAVA a much more elaborate

proxying
/// is required.
/// </remarks>
class ImmutableIDictionary: IDictionary
{
protected readonly IDictionary proxied;
public ImmutableIDictionary(IDictionary proxied) {
if ( proxied == null )
throw new ArgumentException(
"Cannot proxy uninstantiated IDictionary", "proxied");
this.proxied = proxied;
}
#region IDictionary Members
public bool IsReadOnly { get { return true; } }
public IDictionaryEnumerator GetEnumerator()
{ return proxied.GetEnumerator(); }
public object this[object key]
{ get { return proxied[key]; } set { throw new Immutable(); } }
public void Remove(object key) { throw new Immutable(); }
public bool Contains(object key) { return proxied.Contains(key); }
public void Clear() { throw new Immutable(); }
public ICollection Values { get { return proxied.Values; } }
public void Add(object key, object value) { throw new Immutable(); }
public ICollection Keys { get { return proxied.Keys; } }
public bool IsFixedSize { get { return true; } }
#endregion

#region ICollection Members
public bool IsSynchronized { get { return proxied.IsSynchronized; } }
public int Count { get { return proxied.Count; } }
public void CopyTo(Array array, int index) { proxied.CopyTo(array,
index); }
public object SyncRoot { get { return proxied.SyncRoot; } }
#endregion

#region IEnumerable Members
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
IEnumerable e = proxied;
return e.GetEnumerator();
}
#endregion
}

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-


Nov 17 '05 #5
Thank you that was what I was looking for.
"Willy Denoyette [MVP]" <wi*************@telenet.be> schrieb im Newsbeitrag
news:OP**************@TK2MSFTNGP12.phx.gbl...
List.AsReadOnly retuns a read-only wrapper arround the current List.
Willy.

"Matthias Schack" <Sc***********@gmx.de> wrote in message
news:uJ*************@TK2MSFTNGP10.phx.gbl...
Thanks for the answer.

So that means there is no predefined method for getting a readonly List<>
in
.NET 2.0?

This is very bad. Since .NET lacks the const modifier like in C++ there
should at least be a simple solution for that without having to write
readonly wrappers for all collection classes all the time by myself :(

"Helge Jensen" <he**********@slog.dk> schrieb im Newsbeitrag
news:#l**************@TK2MSFTNGP12.phx.gbl...


cody wrote:
> I know I can use ArrayList.ReadOnly() to create a readonly version of

it,
> but how can I achive a similar thing with a generic collection of .NET

2.0?

Implement a proxy for the relevant collection, which throw's on
mutation.

Here is an example on the .NET1.1 IDictionary, I haven't changed to
.NET2 yet -- you should be able to write one for IDictionary<> in .NET2
yourself.

using System.Collections;

class Immutable: Exception
{ public Immutable(): base("Attempt to change immutable object") {} }

/// <summary>
/// Provide immutable access to a dictionary.
/// </summary>
/// <remarks>
/// In JAVA, iterators, as well as the key- and value- parts, of a
dictionary
/// (called Map) allows mutation, so in JAVA a much more elaborate

proxying
/// is required.
/// </remarks>
class ImmutableIDictionary: IDictionary
{
protected readonly IDictionary proxied;
public ImmutableIDictionary(IDictionary proxied) {
if ( proxied == null )
throw new ArgumentException(
"Cannot proxy uninstantiated IDictionary", "proxied");
this.proxied = proxied;
}
#region IDictionary Members
public bool IsReadOnly { get { return true; } }
public IDictionaryEnumerator GetEnumerator()
{ return proxied.GetEnumerator(); }
public object this[object key]
{ get { return proxied[key]; } set { throw new Immutable(); } }
public void Remove(object key) { throw new Immutable(); }
public bool Contains(object key) { return proxied.Contains(key); }
public void Clear() { throw new Immutable(); }
public ICollection Values { get { return proxied.Values; } }
public void Add(object key, object value) { throw new Immutable(); }
public ICollection Keys { get { return proxied.Keys; } }
public bool IsFixedSize { get { return true; } }
#endregion

#region ICollection Members
public bool IsSynchronized { get { return proxied.IsSynchronized; } }
public int Count { get { return proxied.Count; } }
public void CopyTo(Array array, int index) { proxied.CopyTo(array,
index); }
public object SyncRoot { get { return proxied.SyncRoot; } }
#endregion

#region IEnumerable Members
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
IEnumerable e = proxied;
return e.GetEnumerator();
}
#endregion
}

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-



Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Paul Welter | last post by:
Is there anyway to do the following? Type myType = typeof(User); Collection<myType> list = new Collection<myType>(); I know I could just use User instead of myType but have a function that...
8
by: JAL | last post by:
Here is my first attempt at a deterministic collection using Generics, apologies for C#. I will try to convert to C++/cli. using System; using System.Collections.Generic; using System.Text; ...
22
by: Adam Clauss | last post by:
OK, I have class A defined as follows: class A { A(Queue<B> queue) { ... } } Now, I then have a subclass of both classes A and B. The subclass of A (SubA), more specifically is passed a...
4
by: Adam Clauss | last post by:
I ran into a problem a while back when attempting to convert existing .NET 1.1 based code to .NET 2.0 using Generic collections rather than Hashtable, ArrayList, etc. I ran into an issue because...
19
by: Brett Romero | last post by:
Here's a table of data I'm putting into a collection: CodeId CodeGroup CodeSubGroup Type 1 K K.1 Shar1 2 K ...
7
by: Sehboo | last post by:
We have several generic List objects in our project. Some of them have about 1000 items in them. Everytime we have to find something, we have to do a for loop. There is one method which does the...
4
by: mojeza | last post by:
I would like to create generic object which will be used for store of single row of DataTable. Lets say I create class as follow: Public Class Participant Public ParticipantID As Int64 Public...
3
by: dgk | last post by:
I figured that I'd just set the datasource of a gridview to a generic list of classx, but at runtime databind complains: "The data source for GridView with id 'gv1' did not have any properties or...
2
by: SimonDotException | last post by:
I am trying to use reflection in a property of a base type to inspect the properties of an instance of a type which is derived from that base type, when the properties can themselves be instances of...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
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
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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.