473,513 Members | 2,576 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3070


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
9102
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 takes a type and populates a collection then calls SetValue using reflection. How would I create the generic collection to fill it and call SetValue?
8
1817
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; namespace DeterminedGenericCollection { // I got tired of copy and pasting IDisposable
22
13091
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 Queue<SubB>.
4
2207
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 the old code allowed me to do what basically was the following assignment: class SomeClass { private Queue q; SomeClass(Queue q)
19
2307
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 K.1 MD5 3 J J.2 Shar1 I want to get the data in two ways: Codes codes;
7
16657
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 searching, but that method receives the object, and the string to search in that object and runs the FOR loop to find the answer. This is taking...
4
2162
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 LastName As String Public FirstName As String End Class then I get a data from the database to DataTable and create array of
3
6658
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 attributes from which to generate columns. Ensure that your data source has content." The list (of classx) has public properties, which means...
2
4164
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 types derived from that base type, or arrays or generic collections of instances of types derived from that base type. All is well until I come to...
0
7270
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7178
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7397
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7565
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7543
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
4759
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3242
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1612
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
473
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.