C# Generics, where keyword, and attributes.

R

Ricebot

Hi,

I'm playing around with extended List<T> such that I have a
generic list collection that is cloneable (fully, not shallow) and
serializable.

So far the impl looks like this.

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;

[Serializable]
public class CloneableList<T> : List<T>, ICloneable
where T : ICloneable, ISerializable
{
public CloneableList() { }

public CloneableList(int size) : base(size) { }

public object Clone()
{
CloneableList<T> clone = new CloneableList<T>(this.Count);

foreach (T t in this)
{
clone.Add((T)t.Clone());
}

return clone;
}
}

However, I note that the constraint above where T : ISerializable, is
too
strict, as it rules out some of the normal classes that are marked with
the [Serializable] attribute, but do not implement ISerializable (like
System.String for instance)

Is there anyway to use the where keyword to specify that T must
have the [Serializable] attribute? Or is the design of attributes in
C# such that any attributes on T cannot be known at the time that
CloneableList<T> is compiled into, say, CloneableList<String>?

Thanks,

Eric
 
J

Jon Skeet [C# MVP]

Ricebot said:
I'm playing around with extended List<T> such that I have a
generic list collection that is cloneable (fully, not shallow) and
serializable.

Is there anyway to use the where keyword to specify that T must
have the [Serializable] attribute? Or is the design of attributes in
C# such that any attributes on T cannot be known at the time that
CloneableList<T> is compiled into, say, CloneableList<String>?

I don't know that the latter is true, but there's no way of specifying
what you want, unfortunately.

Jon
 
R

Ricebot

Ok, thanks for the feedback!
Ricebot said:
I'm playing around with extended List<T> such that I have a
generic list collection that is cloneable (fully, not shallow) and
serializable.

Is there anyway to use the where keyword to specify that T must
have the [Serializable] attribute? Or is the design of attributes in
C# such that any attributes on T cannot be known at the time that
CloneableList<T> is compiled into, say, CloneableList<String>?

I don't know that the latter is true, but there's no way of specifying
what you want, unfortunately.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top