I have problems wit hthe implementation of a generic sorting algorithm.
We need to implement quicksort and selection sort, and a class which should be sortable using these functions. The functions should be generic, and thus work on other classes as well.
I tested the quicksort. It works perfectly on a List. However, when trying to execute it on my own comparable class, it says:
There is no implicit reference conversion from 'SNIP' to 'System.IComparable'
Do you guys have any idea what the problem can be?
Here is my comparable class:
public class SNIP : IComparable
{
private long lCost { get; set; }
public SNIP(long lCost)
{
this.lCost = lCost;
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
SNIP oOtherPlank = obj as SNIP;
if (oOtherPlank != null)
return this.lCost.CompareTo(oOtherPlank.lCost);
else
throw new ArgumentException("Can only compare SNIPs.");
}
}
Thanks in advance!
Thanks to #Sweeper, the comparable is now fixed.
Like he said, I had to define my class better:
public class SNIP : IComparable<SNIP>
{
private long lCost { get; set; }
public SNIP(long lCost)
{
this.lCost = lCost;
}
public int CompareTo(SNIP obj)
{
if (obj == null) return 1;
SNIP oOtherSnip= obj as SNIP;
if (oOtherSnip!= null)
return this.lCost.CompareTo(oOtherSnip.lCost);
else
throw new ArgumentException("Can only compare SNIPs.");
}
}
It is also important to note that this only works when the argument of the CompareTo method is actually of the right class. I tried defining the class as IComparable before, but it didn't work because the argument in CompareTo was set to an object. By changing both the CompareTo header and the class header, the problem is fixed and the sorting now works.
Thanks a lot :-)
You can implement generic IComparable<SNIP>, not IComparable which is very simple: this is always geater than null and if we compare with not null other we should check lCost.
public class SNIP : IComparable<SNIP>
{
private long lCost { get; set; }
public SNIP(long lCost)
{
this.lCost = lCost;
}
public int CompareTo(SNIP other) => other is null
? 1
: lCost.CompareTo(other.lCost);
}
then you can sort: note that since List<SNIP> is generic, the generic IComparable<SNIP> will be used on sorting.
List<SNIP> list = new List<SNIP>()
{
new SNIP(5),
new SNIP(1),
new SNIP(3),
};
list.Sort();
Related
I've made a code that has an interface and an abstract class to make my main function to work with both objects. As I started to work around my function everything was working perfectly until I needed to get a function from the object itself.
My function is:
void addNode<T>(List<T> genericList) where T : IGraphs{
T genericNode = (T)Activator.CreateInstance(typeof(T));
genericNode.Number = contDirected;
if (genericList.Count > 0)
{
string connectedNode = "";
while (!connectedNode.Equals("0") && genericList.RemainingNodesExist(undirectedGraphs, genericNode))
{
}
}
}
}
Obviously the function is not yet finished but the problem is on my last "while". As I try to get the method "RemainingNodesExist", the IDE gives me an advice saying that List does not have a definition for the method. Im not sure why is that since I have it on my classes:
public interface IGraphs
{
public int Number { get; set; }
public List<int> LinkedNumbers { get; set; }
}
public abstract class AbstractGraphs<T>
{
public abstract bool RemainingNodesExist(List<T> list, T node);
}
And on the classes that inherit from those above:
public class DirectedGraph: AbstractGraphs<DirectedGraph>, IGraphs
{
public int Number { get; set; }
public List<int> LinkedNumbers { get; set; }
public DirectedGraph()
{
Number = Number;
LinkedNumbers = new List<int>();
}
public override bool RemainingNodesExist(List<DirectedGraph> list, DirectedGraph node)
{
int numbersConnected = node.LinkedNumbers.Count;
if (numbersConnected != list.Count)
{
return true;
}
return false;
}
public UndirectedGraph()
{
Number = Number;
LinkedNumbers = new List<int>();
}
public int Number { get; set; }
public List<int> LinkedNumbers { get; set; }
public override bool RemainingNodesExist(List<UndirectedGraph> list, UndirectedGraph node)
{
int numbersConnected = node.LinkedNumbers.Count;
if (numbersConnected != list.Count)
{
return true;
}
return false;
}
To better summarize whats my goal...
I have 2 objects that are exactly the same in properties, but the methods will probably be different in some situations. I used the generic class T because the program will use a list of objects not yet defined that can be any of the two objects mentioned above. What I want my program to do is run the "addNode" function and run the method of both objects based on their type.
Has anyone had to deal with a similar problem or could give me some direction on how to solve this?
I am very suspicious of this code base, it looks way way too complicated.
But to answer your specific question
while (!connectedNode.Equals("0") && genericList.RemainingNodesExist(undirectedGraphs, genericNode))
attempts to call a method on genericList, thats a List<XXX> passed as a parameter
That method (RemainingNodesExist) is defined here
public abstract class AbstractGraphs<T>
{
public abstract bool RemainingNodesExist(List<T> list, T node);
}
Its a method of a class called AbstractGraphs<T>
Which has no relation to List<AnythinG>
Its hard to say what you need to change because this is such a convoluted set of classes.
Maybe if you can explain why you think that method would be callable on a list that might make it clearer
Is there a way to emulate F#'s with keyword in C#? I know it will likely not be as elegant, but I'd like to know if there's any way to handle creating new immutable copies of data structures.
Records in F# are detailed here.
Here's an example of what I'm trying to do. We'll create "immutable" views of data via interfaces, while maintaining mutability in concrete classes. This lets us mutate locally (while working) and then return an immutable interface. This is what we're handling immutability in C#.
public interface IThing
{
double A { get; }
double B { get; }
}
public class Thing : IThing
{
double A { get; set; }
double B { get; set; }
}
However, when it comes time to make a change to the data, it's not very type (or mutability!) safe to cast it back and forth, and it's also a real pain to manually translate each property of the class into a new instance. What if we add a new one? Do I have to go track down each manipulation? I don't want to create future headache when I really only need what I had before, but with [some change].
Example:
// ...
IThing item = MethodThatDoesWork();
// Now I want to change it... how? This is ugly and error/change prone:
IThing changed = new Thing {
A = item.A,
B = 1.5
};
// ...
What are sound strategies for accomplishing this? What have you used in the past?
As there is no syntactic sugar I am aware of you'll have to either:
do it by hand (see below)
use some reflection/automapper (not a fan of this)
use some AOP techniques (neither a fan of those)
At least this is what I can think of right now.
I don't think the last two are a good idea because you bring on the big machinery to solve a very easy problem.
Yes when you have thousands of data-structures you might rethink this, but if you only have a couple of them I would not use it.
So what's left is basically smart-constructors and stuff like this - here is a simple example of how you could do it (note that you don't really need all of this - pick and choose) - it's basically missusing null/nullable to look for what you need - better options to this might be overloads or something like an Option<T> data-type but for now I think you get it:
class MyData
{
private readonly int _intField;
private readonly string _stringField;
public MyData(int intField, string stringField)
{
_intField = intField;
_stringField = stringField;
}
public MyData With(int? intValue = null, string stringValue = null)
{
return new MyData(
intValue ?? _intField,
stringValue ?? _stringField);
}
// should obviously be put into an extension-class of some sort
public static MyData With(/*this*/ MyData from, int? intValue = null, string stringValue = null)
{
return from.With(intValue, stringValue);
}
public int IntField
{
get { return _intField; }
}
public string StringField
{
get { return _stringField; }
}
}
To add to Carsten's correct answer, there's no way to do this in C# because it's not in the language. In F#, it's a language feature, where succinct record declaration syntax expands to quite a bit of IL. C# doesn't have that language feature (yet).
This is one of the reasons I no longer like to work in C#, because there's too much overhead compared to doing the same thing in F#. Still, sometimes I have to work in C# for one reason or the other, and when that happens, I bite the bullet and write the records by hand.
As an example, the entire AtomEventSource library is written in C#, but with immutable records. Here's an abbreviated example of the AtomLink class:
public class AtomLink : IXmlWritable
{
private readonly string rel;
private readonly Uri href;
public AtomLink(string rel, Uri href)
{
if (rel == null)
throw new ArgumentNullException("rel");
if (href == null)
throw new ArgumentNullException("href");
this.rel = rel;
this.href = href;
}
public string Rel
{
get { return this.rel; }
}
public Uri Href
{
get { return this.href; }
}
public AtomLink WithRel(string newRel)
{
return new AtomLink(newRel, this.href);
}
public AtomLink WithHref(Uri newHref)
{
return new AtomLink(this.rel, newHref);
}
public override bool Equals(object obj)
{
var other = obj as AtomLink;
if (other != null)
return object.Equals(this.rel, other.rel)
&& object.Equals(this.href, other.href);
return base.Equals(obj);
}
public override int GetHashCode()
{
return
this.Rel.GetHashCode() ^
this.Href.GetHashCode();
}
// Additional members removed for clarity.
}
Apart from the overhead of having to type all of this, it's also been bothering me that if you're doing (dogmatic) Test-Driven Development (which you don't have to), you'd want to test these methods as well.
Using tools like AutoFixture and SemanticComparison, though, you can make it somewhat declarative. Here's an example from AtomLinkTests:
[Theory, AutoAtomData]
public void WithRelReturnsCorrectResult(
AtomLink sut,
string newRel)
{
AtomLink actual = sut.WithRel(newRel);
var expected = sut.AsSource().OfLikeness<AtomLink>()
.With(x => x.Rel).EqualsWhen(
(s, d) => object.Equals(newRel, d.Rel));
expected.ShouldEqual(actual);
}
Here, it's still relatively verbose, but you can easily refactor this to a generic method, so that each test case becomes a one-liner.
It's still a bother, so even if you're writing most of your code in C#, you might consider defining your immutable types in a separate F# library. Viewed from C#, F# records look like 'normal' immutable classes like AtomLink above. Contrary to some other F# types like discriminated unions, F# records are perfectly consumable from C#.
Here is my attempt at emulating immutable mutations in C# via concrete classes. Some magic via generics, which includes type safety!
class Program
{
static void Main(string[] args)
{
var r = new Random();
// A new class item
IDataItem item = new DataItem
{
A = r.NextDouble(),
B = r.NextDouble(),
C = r.NextDouble(),
D = r.NextDouble()
};
// Type hinting here helps with inference
// The resulting `newItem` is an "immutable" copy of the source item
IDataItem newItem = item.With((DataItem x) =>
{
x.A = 0;
x.C = 2;
});
// This won't even compile because Bonkers doesn't implement IDataItem!
// No more casting madness and runtime errors!
IBonkers newItem2 = item.With((Bonkers x) => { /* ... */ });
}
}
// A generic record interface to support copying, equality, etc...
public interface IRecord<T> : ICloneable,
IComparable,
IComparable<T>,
IEquatable<T>
{
}
// Immutable while abstract
public interface IDataItem : IRecord<IDataItem>
{
double A { get; }
double B { get; }
double C { get; }
double D { get; }
}
// Mutable while concrete
public class DataItem : IDataItem
{
public double A { get; set; }
public double B { get; set; }
public double C { get; set; }
public double D { get; set; }
public object Clone()
{
// Obviously you'd want to be more explicit in some cases (internal reference types, etc...)
return this.MemberwiseClone();
}
public int CompareTo(object obj)
{
// Boilerplate...
throw new NotImplementedException();
}
public int CompareTo(IDataItem other)
{
// Boilerplate...
throw new NotImplementedException();
}
public bool Equals(IDataItem other)
{
// Boilerplate...
throw new NotImplementedException();
}
}
// Extension method(s) in a static class!
public static class Extensions
{
// Generic magic helps you accept an interface, but work with a concrete type
// Note how the concrete type must implement the provided interface! Type safety!
public static TInterface With<TInterface, TConcrete>(this TInterface item, Action<TConcrete> fn)
where TInterface : class, ICloneable
where TConcrete : class, TInterface
{
var n = (TInterface)item.Clone() as TConcrete;
fn(n);
return n;
}
}
// A sample interface to show type safety via generics
public interface IBonkers : IRecord<IBonkers> { }
// A sample class to show type safety via generics
public class Bonkers : IBonkers
{
public object Clone()
{
throw new NotImplementedException();
}
public int CompareTo(object obj)
{
throw new NotImplementedException();
}
public int CompareTo(IBonkers other)
{
throw new NotImplementedException();
}
public bool Equals(IBonkers other)
{
throw new NotImplementedException();
}
}
I'd like to compare two custom class objects of the same type. The custom class being compared has a List property which is filled with items of another custom type. Is this possible by inheriting IEquatable?
I couldn't figure out how to make this work by modifying MSDN's code to compare class objects containing List properties of a custom type.
I did successfully derive from the EqualityComparer class to make a separate comparison class (code below), but I'd like to implement the comparison ability in the actual classes being compared. Here's what I have so far:
EDIT: This doesn't work after all. My apologies - I've been working on this awhile and I may have pasted incorrect example code. I'm working on trying to find my working solution...
class Program
{
static void Main(string[] args)
{
// Test the ContractComparer.
Contract a = new Contract("Contract X", new List<Commission>() { new Commission(1), new Commission(2), new Commission(3) });
Contract b = new Contract("Contract X", new List<Commission>() { new Commission(1), new Commission(2), new Commission(3) });
ContractComparer comparer = new ContractComparer();
Console.WriteLine(comparer.Equals(a, b));
// Output returns True. I can't get this to return
// True when I inherit IEquatable in my custom classes
// if I include the list property ("Commissions") in my
// comparison.
Console.ReadLine();
}
}
public class Contract
{
public string Name { get; set; }
public List<Commission> Commissions { get; set; }
public Contract(string name, List<Commission> commissions)
{
this.Name = name;
this.Commissions = commissions;
}
}
public class Commission
{
public int ID;
public Commission(int id)
{
this.ID = id;
}
}
public class ContractComparer : IEqualityComparer<Contract>
{
public bool Equals(Contract a, Contract b)
{
//Check whether the objects are the same object.
if (Object.ReferenceEquals(a, b)) return true;
//Check whether the contracts' properties are equal.
return a != null && b != null && a.Name.Equals(b.Name) && a.Commissions.Equals(b.Commissions);
}
public int GetHashCode(Contract obj)
{
int hashName = obj.Name.GetHashCode();
int hashCommissions = obj.Commissions.GetHashCode();
return hashName ^ hashCommissions;
}
}
You have to implement some kind of comparer for Commission, e.g. by implementing Commission : IEquatable<Commission>, then use it:
... && a.Commissions.SequenceEqual(b.Commissions)
I have a class that is IComparable:
public class a : IComparable
{
public int Id { get; set; }
public string Name { get; set; }
public a(int id)
{
this.Id = id;
}
public int CompareTo(object obj)
{
return this.Id.CompareTo(((a)obj).Id);
}
}
When I add a list of object of this class to a hash set:
a a1 = new a(1);
a a2 = new a(2);
HashSet<a> ha = new HashSet<a>();
ha.add(a1);
ha.add(a2);
ha.add(a1);
Everything is fine and ha.count is 2, but:
a a1 = new a(1);
a a2 = new a(2);
HashSet<a> ha = new HashSet<a>();
ha.add(a1);
ha.add(a2);
ha.add(new a(1));
Now ha.count is 3.
Why doesn't HashSet respect a's CompareTo method.
Is HashSet the best way to have a list of unique objects?
It uses an IEqualityComparer<T> (EqualityComparer<T>.Default unless you specify a different one on construction).
When you add an element to the set, it will find the hash code using IEqualityComparer<T>.GetHashCode, and store both the hash code and the element (after checking whether the element is already in the set, of course).
To look an element up, it will first use the IEqualityComparer<T>.GetHashCode to find the hash code, then for all elements with the same hash code, it will use IEqualityComparer<T>.Equals to compare for actual equality.
That means you have two options:
Pass a custom IEqualityComparer<T> into the constructor. This is the best option if you can't modify the T itself, or if you want a non-default equality relation (e.g. "all users with a negative user ID are considered equal"). This is almost never implemented on the type itself (i.e. Foo doesn't implement IEqualityComparer<Foo>) but in a separate type which is only used for comparisons.
Implement equality in the type itself, by overriding GetHashCode and Equals(object). Ideally, implement IEquatable<T> in the type as well, particularly if it's a value type. These methods will be called by the default equality comparer.
Note how none of this is in terms of an ordered comparison - which makes sense, as there are certainly situations where you can easily specify equality but not a total ordering. This is all the same as Dictionary<TKey, TValue>, basically.
If you want a set which uses ordering instead of just equality comparisons, you should use SortedSet<T> from .NET 4 - which allows you to specify an IComparer<T> instead of an IEqualityComparer<T>. This will use IComparer<T>.Compare - which will delegate to IComparable<T>.CompareTo or IComparable.CompareTo if you're using Comparer<T>.Default.
Here's clarification on a part of the answer that's been left unsaid: The object type of your HashSet<T> doesn't have to implement IEqualityComparer<T> but instead just has to override Object.GetHashCode() and Object.Equals(Object obj).
Instead of this:
public class a : IEqualityComparer<a>
{
public int GetHashCode(a obj) { /* Implementation */ }
public bool Equals(a obj1, a obj2) { /* Implementation */ }
}
You do this:
public class a
{
public override int GetHashCode() { /* Implementation */ }
public override bool Equals(object obj) { /* Implementation */ }
}
It is subtle, but this tripped me up for the better part of a day trying to get HashSet to function the way it is intended. And like others have said, HashSet<a> will end up calling a.GetHashCode() and a.Equals(obj) as necessary when working with the set.
HashSet uses Equals and GetHashCode().
CompareTo is for ordered sets.
If you want unique objects, but you don't care about their iteration order, HashSet<T> is typically the best choice.
constructor HashSet receive object what implement IEqualityComparer for adding new object.
if you whant use method in HashSet you nead overrride Equals, GetHashCode
namespace HashSet
{
public class Employe
{
public Employe() {
}
public string Name { get; set; }
public override string ToString() {
return Name;
}
public override bool Equals(object obj) {
return this.Name.Equals(((Employe)obj).Name);
}
public override int GetHashCode() {
return this.Name.GetHashCode();
}
}
class EmployeComparer : IEqualityComparer<Employe>
{
public bool Equals(Employe x, Employe y)
{
return x.Name.Trim().ToLower().Equals(y.Name.Trim().ToLower());
}
public int GetHashCode(Employe obj)
{
return obj.Name.GetHashCode();
}
}
class Program
{
static void Main(string[] args)
{
HashSet<Employe> hashSet = new HashSet<Employe>(new EmployeComparer());
hashSet.Add(new Employe() { Name = "Nik" });
hashSet.Add(new Employe() { Name = "Rob" });
hashSet.Add(new Employe() { Name = "Joe" });
Display(hashSet);
hashSet.Add(new Employe() { Name = "Rob" });
Display(hashSet);
HashSet<Employe> hashSetB = new HashSet<Employe>(new EmployeComparer());
hashSetB.Add(new Employe() { Name = "Max" });
hashSetB.Add(new Employe() { Name = "Solomon" });
hashSetB.Add(new Employe() { Name = "Werter" });
hashSetB.Add(new Employe() { Name = "Rob" });
Display(hashSetB);
var union = hashSet.Union<Employe>(hashSetB).ToList();
Display(union);
var inter = hashSet.Intersect<Employe>(hashSetB).ToList();
Display(inter);
var except = hashSet.Except<Employe>(hashSetB).ToList();
Display(except);
Console.ReadKey();
}
static void Display(HashSet<Employe> hashSet)
{
if (hashSet.Count == 0)
{
Console.Write("Collection is Empty");
return;
}
foreach (var item in hashSet)
{
Console.Write("{0}, ", item);
}
Console.Write("\n");
}
static void Display(List<Employe> list)
{
if (list.Count == 0)
{
Console.WriteLine("Collection is Empty");
return;
}
foreach (var item in list)
{
Console.Write("{0}, ", item);
}
Console.Write("\n");
}
}
}
I came here looking for answers, but found that all the answers had too much info or not enough, so here is my answer...
Since you've created a custom class you need to implement GetHashCode and Equals. In this example I will use a class Student instead of a because it's easier to follow and doesn't violate any naming conventions. Here is what the implementations look like:
public override bool Equals(object obj)
{
return obj is Student student && Id == student.Id;
}
public override int GetHashCode()
{
return HashCode.Combine(Id);
}
I stumbled across this article from Microsoft that gives an incredibly easy way to implement these if you're using Visual Studio. In case it's helpful to anyone else, here are complete steps for using a custom data type in a HashSet using Visual Studio:
Given a class Student with 2 simple properties and an initializer
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public Student(int id)
{
this.Id = id;
}
}
To Implement IComparable, add : IComparable<Student> like so:
public class Student : IComparable<Student>
You will see a red squiggly appear with an error message saying your class doesn't implement IComparable. Click on suggestions or press Alt+Enter and use the suggestion to implement it.
You will see the method generated. You can then write your own implementation like below:
public int CompareTo(Student student)
{
return this.Id.CompareTo(student.Id);
}
In the above implementation only the Id property is compared, name is ignored. Next right-click in your code and select Quick actions and refactorings, then Generate Equals and GetHashCode
A window will pop up where you can select which properties to use for hashing and even implement IEquitable if you'd like:
Here is the generated code:
public class Student : IComparable<Student>, IEquatable<Student> {
...
public override bool Equals(object obj)
{
return Equals(obj as Student);
}
public bool Equals(Student other)
{
return other != null && Id == other.Id;
}
public override int GetHashCode()
{
return HashCode.Combine(Id);
}
}
Now if you try to add a duplicate item like shown below it will be skipped:
static void Main(string[] args)
{
Student s1 = new Student(1);
Student s2 = new Student(2);
HashSet<Student> hs = new HashSet<Student>();
hs.Add(s1);
hs.Add(s2);
hs.Add(new Student(1)); //will be skipped
hs.Add(new Student(3));
}
You can now use .Contains like so:
for (int i = 0; i <= 4; i++)
{
if (hs.Contains(new Student(i)))
{
Console.WriteLine($#"Set contains student with Id {i}");
}
else
{
Console.WriteLine($#"Set does NOT contain a student with Id {i}");
}
}
Output:
I have a concrete class that contains a collection of another concrete class. I would like to expose both classes via interfaces, but I am having trouble figuring out how I can expose the Collection<ConcreteType> member as a Collection<Interface> member.
I am currently using .NET 2.0
The code below results in a compiler error:
Cannot implicitly convert type
'System.Collections.ObjectModel.Collection<Nail>' to
'System.Collections.ObjectModel.Collection<INail>'
The commented attempt to cast give this compiler error:
Cannot convert type
'System.Collections.ObjectModel.Collection<Nail>' to
'System.Collections.ObjectModel.Collection<INail>' via a
reference conversion, boxing conversion, unboxing conversion, wrapping
conversion, or null type conversion.
Is there any way to expose the collection of concrete types as a collection of interfaces or do I need to create a new collection in the getter method of the interface?
using System.Collections.ObjectModel;
public interface IBucket
{
Collection<INail> Nails
{
get;
}
}
public interface INail
{
}
internal sealed class Nail : INail
{
}
internal sealed class Bucket : IBucket
{
private Collection<Nail> nails;
Collection<INail> IBucket.Nails
{
get
{
//return (nails as Collection<INail>);
return nails;
}
}
public Bucket()
{
this.nails = new Collection<Nail>();
}
}
C# 3.0 generics are invariant. You can't do that without creating a new object. C# 4.0 introduces safe covariance/contravariance which won't change anything about read/write collections (your case) anyway.
Just define nails as
Collection<INail>
Why not just return it as an interface, just have all your public methods in the interface, that way you don't have this problem, and, if you later decide to return another type of Nail class then it would work fine.
What version of .Net are you using?
If you are using .net 3.0+, you can only achieve this by using System.Linq.
Check out this question, which solved it for me.
There is one solution that might not be quite what you are asking for but could be an acceptable alternative -- use arrays instead.
internal sealed class Bucket : IBucket
{
private Nail[] nails;
INail[] IBucket.Nails
{
get { return this.nails; }
}
public Bucket()
{
this.nails = new Nail[100];
}
}
(If you end up doing something like this, keep in mind this Framework Design Guidelines note: generally arrays shouldn't be exposed as properties, since they are typically copied before being returned to the caller and copying is an expensive operation to do inside an innocent property get.)
use this as the body of your property getter:
List<INail> tempNails = new List<INail>();
foreach (Nail nail in nails)
{
tempNails.Add(nail);
}
ReadOnlyCollection<INail> readOnlyTempNails = new ReadOnlyCollection<INail>(tempNails);
return readOnlyTempNails;
That is a tad bit of a hacky solution but it does what you want.
Edited to return a ReadOnlyCollection. Make sure to update your types in IBucket and Bucket.
You can add some generics. Fits better, more strongly coupled.
public interface IBucket<T> where T : INail
{
Collection<T> Nails
{
get;
}
}
public interface INail
{
}
internal sealed class Nail : INail
{
}
internal sealed class Bucket : IBucket<Nail>
{
private Collection<Nail> nails;
Collection<Nail> IBucket<Nail>.Nails
{
get
{
return nails; //works
}
}
public Bucket()
{
this.nails = new Collection<Nail>();
}
}
This way the Collection<Nail> you return from Bucket class can only ever hold Nails. Any other INail wont go into it. This may or may not be better depending on what you want.
Only if you want Collection<INail> (the interface property) you return from Bucket to hold other INails (than Nails) then you may try the below approach. But there is a problem. On one side you say you want to use a private Collection<Nail> in Bucket class and not a Collection<INail> because you dont want to accidentally add other INails from Bucket class into it but on the other side you will have to add other INails from outside of Bucket class. This is not possible on the same instance. Compiler stops you from accidentally adding any INail to a Collection<Nail>. One way is to return a different instance of Collection<INail> from your Bucket class from the existing Collection<Nail>. This is less efficient, but could be the semantics you are after. Note that this is conceptually different from above
internal sealed class Bucket : IBucket
{
private Collection<Nail> nails;
Collection<INail> IBucket<Nail>.Nails
{
get
{
List<INail> temp = new List<INail>();
foreach (Nail nail in nails)
temp.Add(nail);
return new Collection<INail>(temp);
}
}
public Bucket()
{
this.nails = new Collection<Nail>();
}
}
C# doesn't support generic collections covariance (it's only supported for arrays).
I use an adapter class in such cases. It just redirects all calls to the actual collection, converting values to the required type (doesn't require copying all list values to the new collection).
Usage looks like this:
Collection<INail> IBucket.Nails
{
get
{
return new ListAdapter<Nail, INail>(nails);
}
}
// my implementation (it's incomplete)
public class ListAdapter<T_Src, T_Dst> : IList<T_Dst>
{
public ListAdapter(IList<T_Src> val)
{
_vals = val;
}
IList<T_Src> _vals;
protected static T_Src ConvertToSrc(T_Dst val)
{
return (T_Src)((object)val);
}
protected static T_Dst ConvertToDst(T_Src val)
{
return (T_Dst)((object)val);
}
public void Add(T_Dst item)
{
T_Src val = ConvertToSrc(item);
_vals.Add(val);
}
public void Clear()
{
_vals.Clear();
}
public bool Contains(T_Dst item)
{
return _vals.Contains(ConvertToSrc(item));
}
public void CopyTo(T_Dst[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public int Count
{
get { return _vals.Count; }
}
public bool IsReadOnly
{
get { return _vals.IsReadOnly; }
}
public bool Remove(T_Dst item)
{
return _vals.Remove(ConvertToSrc(item));
}
public IEnumerator<T_Dst> GetEnumerator()
{
foreach (T_Src cur in _vals)
yield return ConvertToDst(cur);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public override string ToString()
{
return string.Format("Count = {0}", _vals.Count);
}
public int IndexOf(T_Dst item)
{
return _vals.IndexOf(ConvertToSrc(item));
}
public void Insert(int index, T_Dst item)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
public T_Dst this[int index]
{
get { return ConvertToDst(_vals[index]); }
set { _vals[index] = ConvertToSrc(value); }
}
}
you could use the Cast extension
nails.Cast<INail>()
I can't test it here to provide a more comprehensive example, as we are using .NET 2.0 at work (gripe gripe), but I did have a similar question here