I am trying to implement a generic comparer (for a sort) for all objects that have a Text property... so two ASP.net textboxes can be compared, two labels or in this specific case two RadTreeNodes in a telerik RadTreeView (as long as they have a Text property). So I've put the following together to try and so this but get an error as follows:
I have the following code:
public class TextComparer<T> : IComparer
where T : IHasTextProperty
{
public int Compare(object a, object b)
{
T nodeA = (T)a;
T nodeB = (T)b;
return nodeA.Text.CompareTo(nodeB.Text);
}
}
public interface IHasTextProperty
{
string Text { get; set; }
}
Then plan on using it like so...
Array.Sort(nodes, new TextComparer<RadTreeNode>());
but get the following message :
Error 6613 The type 'Telerik.Web.UI.RadTreeNode' cannot be used as
type parameter 'T' in the generic type or method 'TextComparer'.
There is no implicit reference conversion from
'Telerik.Web.UI.RadTreeNode' to 'IHasTextProperty'
I'm sure this is a simple fix, but I'm just a little stumped as to how to fix it.
You are attempting to perform duck-typing in C#, which doesn't support duck-typing. In some languages, you can match a type based on it having a certain property, such as Text in this case. This only works if the language supports this technique.
With C#, a class must explicitly implement an interface for it to be deemed to have that interface's type. Telerik.Web.UI.RadTreeNode doesn't implement IHasTextProperty. T is contrained to types that implement IHasTextProperty, and so you get the error you see.
You really can't use generics in this case. You need to test whether a and b have a Text property. This can be done using reflection or by using dynamic. Neither solution will be as neat as what you were attempting to do unfortunately.
System.Web.UI provides its own IHasTextProperty namely ITextControl (msdn), which behaves exactly like your IHasTextProperty. The downside is that you can not be sure RadTreeNode (or any other 3rd party control) implements this interface.
The only way to be sure is to remove this check from compile time and put it into runtime via reflection, which is quite simple but perhaps not what you want. In case you still want to use it here's an example using an ArgumentException in the TextComparer's constructor to ensure only valid objects are compared.
public class TextComparer<T> : IComparer
{
private bool HasTextProperty(Type t)
{
return (t.GetProperty("Text", typeof(string)) != null);
}
private string GetTextPropertyValue(object obj)
{
return obj.GetType().GetProperty("Text", typeof(string)).GetValue(obj) as string;
}
public TextComparer()
{
if (!HasTextProperty(typeof(T))) throw new ArgumentException(string.Format("{0} doesn't provide a Text property", typeof(T).Name), "T");
}
public int Compare(object x, object y)
{
return GetTextPropertyValue(x).CompareTo(GetTextPropertyValue(y));
}
}
Related
Please check the following codes segments:
public interface ICountable { }
public class Counter<T>
where T : ICountable
{
public int Count(IEnumerable<T> items)
{
return 0;
}
public int Count(T Item)
{
return 0;
}
}
public class Counter
{
public int Count<T>(IEnumerable<T> items)
where T : ICountable
{
return 0;
}
public int Count<T>(T Item)
where T : ICountable
{
return 0;
}
}
The two versions of Counter differ only in the specification of the generic parameter. One of them defines as a generic type parameter, the other as a generic argument. Both restrict the method arguments to implement the ICountable interface. I will call them specific and non specific respectively.
Now, I am defining a class that implements the ICountable interface, and a collection of instances:
public class CItem : ICountable { }
var countables = new List<CItem>();
Then, I would like to use both Counter classes on the collection.
var specific = new Counter<CItem>();
var nonspecific = new Counter();
specific.Count(countables);
nonspecific.Count(countables);
The specific counter recognizes that the countables collection should fall into the signature int Count(IEnumerable), but the non specific version does not. I get the error:
The type 'System.Collections.Generic.List<CItem>' cannot be used as
type parameter 'T' in the generic type or method
'Counter.Count<T>(T)'. There is no implicit reference conversion from
List<CItem>' to ICountable.
It seems that the non specific version uses the wrong signature for the collection.
Why do they behave differently?
How can the non specific version be specified in order to behave the same as the other?
Note: I know this example is not realistic. However, I faced this problem in a quite complicate scenario with extension methods. I use these classes for the sake of simplicity
Thanks in advance
The problem with nonspecific class is that compiler doesn't know the type T in compile time that's why it cannot select correct overload for method Count<T>(). However if you set generic type constraints compiler now knows what type to expect...
If you'll comment out your method with signature public int Count<T>(T Item) it'll compile because it'll use method with correct signature (which is public int Count<T>(IEnumerable<T> items))
It'll also compile and run if you help compiler to infer type by casting your List to IEnumerable<CItem> explicitly :
nonspecific.Count(countables as IEnumerable<CItem>);
Have a look at simplified scenario :
static string A<T>(IEnumerable<T> collection)
{
return "method for ienumerable";
}
static string A<T>(T item)
{
return "method for single element";
}
static void Main(string[] args)
{
List<int> numbers = new List<int>() { 5, 3, 7 };
Console.WriteLine(A(numbers));
}
Output : "method for single element"
If I remember correctly (will try to find a reference in the specification), the T method is chosen because it's an exact match for the type.
The type inference, correctly identifies that both generic methods are applicable, as Count<CItem>(IEnumerable<CItem> items) and Count<List<CItem>>(List<CItem> items). However, the first one loses in the overload resolution, as the second one is more specific. The constraints only come in play after that, so you get a compile time error.
If you declare your countables using
IEnumerable<CItem> countables = new List<CItem>();
then the choice becomes Count<CItem>(IEnumerable<CItem> items) and Count<IEnumerable<CItem>>(IEnumerable<CItem> items) and the first one wins the overload resolution.
In my opinion, the reason why the compiler thinks that you are calling Counter.Count(T) instead of Counter.Count< T >(IEnumerable< T >) is because the later one requires a conversion from List to IEnumerable. And that has a priority less than using the former signature Counter.Count(T), which result in an error.
I think it's better that you change the method name of the one taking an IEnumerble as the argument into something like CountAll. The some thing .NET framework does for List.Remove and List.RemoveAll. It's a good practice to make your code more specific rather than letting the compiler to do all the decisions.
Long story short, I would like to be able to store generics using different type parameters in an array, by using a parent type to all the types used. MSDN mentioned it was impossible, as generics were invariant types, but a comment stated that this changed since the 4.0 framework.
Here is a basic example of what I would like to do:
public class Animal
{
}
public class Dog : Animal
{
}
public class Cat : Animal
{
}
public class MyGeneric<T>
{ }
public class MyInheritedGeneric<T> : MyGeneric<T>
{ }
static void Main(string[] args)
{
MyGeneric<Animal>[] myGenericArray = new MyGeneric<Animal>[]
{
new MyGeneric<Dog>(),
new MyInheritedGeneric<Cat>()
};
}
This returns the similar errors:
Cannot implicitly convert type
'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Dog>' to
'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Animal>'
Cannot implicitly convert type
'InheritanceTest.Program.MyInheritedGeneric<InheritanceTest.Program.Cat>'
to 'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Animal>'
Is there any way to store generics in an array using the parent class of the type, or is this simply impossible? I really hope it is possible, otherwise it will make my program a nightmare...
EDIT: A bit more context!
I am making classes to generate enemies in a game. I call them Templates (nothing to do with actual template classes, I could very well have called them Blueprints or Factories). An enemy constructor takes in a Template, which it uses to determine its own values. When the game loads, the templates are used to generate all enemies, using their Generate() function, which returns an array of the corresponding type they are assigned to produce. All the objects to be created with a template are to have a constructor taking a template as their sole parameter.
public class Template<T>
{
protected static Random random = new Random();
protected int _amount;
public int Amount
{
get { return _amount; }
}
public virtual T CreateInstance()
{
return (T)Activator.CreateInstance(typeof(T), this);
}
public virtual T[] Generate()
{
T[] objects = new T[Amount];
for (int i = 0; i < Amount; ++i)
objects[i] = CreateInstance();
return objects;
}
}
Here is a summary of the BasicZombie.cs file, which contains the actual enemy class and the template.
class Tpl_BasicZombie : Tpl_Enemy<BasicZombie>
{
public Tpl_BasicZombie()
{
_hp = 4;
_speed = 3;
_amount = 10;
}
}
class BasicZombie : GroundEnemy
{
public BasicZombie(Tpl_BasicZombie template)
: base(template, TextureManager.Get("zombie_base"), 1, 8)
{ }
public void StuffHappens()
{ }
}
When loading the game, I would like to go through all the templates in an array to load enemies from them. I know that I could do this manually, but every time I will create a new type of enemy I would need to add it manually to the code (thus probably forgetting more than once).
My two options were:
1- Use a generic, and the above problem ensues.
2- Use a non-generic, and store the type inside, which would anchor the return type Generate() function. This would mean the generate function would output an array of objects, array which would need to be converted to the suitable type every single time a template generates an array of enemies.
I have a space in my head that tells me there is an elegant solution to all this, and I hope it is right!
Yes, C# 4 supports generic variants - but only in the declarations of interfaces and delegates, so you won't be able to do it in this case. Of course you could potentially create an interface:
public interface IGeneric<out T>
and then implement that in your classes, at which point you could create an IGeneric<Animal>.
If you can give more details about what you're trying to achieve, we may be able to help you find an alternative approach.
Jon Skeet's info aside, you might be able to do something like this:
public MyGeneric<T2> ToOtherType<T2>()
{
if (typeof(T2).IsAssignableFrom(typeof(T)))
{
// todo: get the object
return null;
}
else
throw new ArgumentException();
}
new MyGeneric<Dog>().ToOtherType<Animal>(),
new MyInheritedGeneric<Cat>().ToOtherType<Animal>()
If an array is going to hold more than one type of item, the items are going to have to be stored in heap objects which are separate from the array itself (if some of the types are structs, they'll have to either be boxed or stored as a field in a generic type which derives from a non-generic one). In most cases, the simplest thing to do will be to identify a common ancestor type for everything you'll be storing in the array, and simply typecast array elements as needed. There are a few cases where that won't be feasible, however. If, for example, your collection is going to hold objects whose type is unknown but is constrained to more than one interface, it will be necessary to pass those objects to generic routines whose method type parameter is similarly constrained, and the types that may be passed to your routine have no common ancestor which satisfies all constraints, there won't be any single type to which all members of your collection can be cast that would allow them to be passed as a suitable generic.
If the objects in your collection will only be passed to a small number of routines, it may be possible to have the generic method which adds items construct delegates to suitably invoke all the necessary routines and store those delegates as part of the collection. Lambda expressions or anonymous delegates may be convenient for this.
For example, suppose one will need to be able to feed items that are stored in a list to the Wibble<T> method of various IWibbler objects and the Wobble<T> method of various IWobbler objects, where the T types have interface constraints I1 and I2.
interface IWibbler { void Wibble<T>(T param, int param) where T : I1,I2; }
interface IWobbler { void Wobble<T>(T param, string param) where T: I1,I2; }
private struct WibbleWobbleDelegateSet
{
public Action<IWibbler, int> Wibble;
public Action<IWobbler, string> Wobble;
static WibbleWobbleDelegateSet Create<T>(T param) where T: I1, I2
{
var ret = new WibbleWobbleDelegateSet ();
ret.Wibble = (IWibbler wibbler, int p2) => { wibbler.Wibble<T>(param, p2); };
ret.Wobble = (IWobbler wobbler, string p2) => { wobbler.Wobble<T>(param, p2); };
return ret;
}
}
Calling WibbleWobbleDelegateSet.Create<T>(T param), with a suitably-constrained param, will yield a non-generic structure which contains delegates that can be used to pass the parameter supplied at struct creation to any IWibbler.Wibble<T>() or IWobbler.Wobble<T>() method.
This approach is only directly usable if the list of routines that will be called is known. If one needs to be able to call arbitrary routines with constrained generic parameters, it's possible to do that either with some tricky interfaces or with Reflection, but such things get more complicated.
I have followed the suggestions from this post to try and get Distinct() working in my code but I am still having issues. Here are the two objects I am working with:
public class InvoiceItem : IEqualityComparer<InvoiceItem>
{
public InvoiceItem(string userName, string invoiceNumber, string invoiceAmount)
{
this.UserName = userName;
this.InvoiceNumber= invoiceNumber;
this.InvoiceAmount= invoiceAmount;
}
public string UserName { get; set; }
public string InvoiceNumber { get; set; }
public double InvoiceAmount { get; set; }
public bool Equals(InvoiceItem left, InvoiceItem right)
{
if ((object)left.InvoiceNumber == null && (object)right.InvoiceNumber == null) { return true; }
if ((object)left.InvoiceNumber == null || (object)right.InvoiceNumber == null) { return false; }
return left.InvoiceNumber == right.InvoiceNumber;
}
public int GetHashCode(InvoiceItem item)
{
return item.InvoiceNumber == null ? 0 : item.InvoiceNumber.GetHashCode();
}
}
public class InvoiceItems : List<InvoiceItem>{ }
My goal is to populate an InvoiceItems object (we will call it aBunchOfInvoiceItems) with a couple thousand InvoiceItem objects and then do:
InvoiceItems distinctItems = aBunchOfInvoiceItems.Distinct();
When I set this code up and run it, I get an error that says
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'InvoiceReader.Form1.InvoiceItems'. An explicit conversion exists (are you missing a cast?)
I don't understand how to fix this. Should I be taking a different approach? Any suggestions are greatly appreciated.
Distinct returns a generic IEnumerable<T>. It does not return an InvoiceItems instance. In fact, behind the curtains it returns a proxy object that implements an iterator that is only accessed on demand (i.e. as you iterate over it).
You can explicitly coerce it into a List<> by calling .ToList(). You still need to convert it to your custom list type, though. The easiest way is probably to have an appropriate constructor, and calling that:
public class InvoiceItems : List<InvoiceItem> {
public InvoiceItems() { }
// Copy constructor
public InvoiceItems(IEnumerable<InvoiceItems> other) : base(other) { }
}
// …
InvoiceItems distinctItems = new InvoiceItems(aBunchOfInvoiceItems.Distinct());
Konrad Rudolph's answer should tackle your compilation problems. There is one another important semantic correctness issue here that has been missed: none of your equality-logic is actually going to be used.
When a comparer is not provided to Distinct, it uses EqualityComparer<T>.Default. This is going to try to use the IEquatable<T> interface, and if this is missing, falls back on the plain old Equals(object other) method declared on object. For hashing, it will use the GetHashCode() method, also declared on object. Since the interface hasn't been implemented by your type, and none of the aforementioned methods have been overriden, there's a big problem: Distinct will just fall back on reference-equality, which is not what you want.
Tthe IEqualityComparer<T> interface is typically used when one wants to write an equality-comparer that is decoupled from the type itself. On the other hand, when a type wants to be able to compare an instance of itself with another; it typically implements IEquatable<T>. I suggest one of:
Get InvoiceItem to implement IEquatable<InvoiceItem> instead.
Move the comparison logic to a separate InvoiceItemComparer : IEqualityComparer<InvoiceItem> type, and then call invoiceItems.Distinct(new InvoiceItemComparer());
If you want a quick hack with your existing code, you can do invoiceItems.Distinct(new InvoiceItem());
Quite simply, aBunchOfInvoiceItems.Distinct() returns an IEnumerable<InvoiceItem> and you are trying to assign that to something that is not an IEnumerable<InvoiceItem>.
However, the base class of InvoiceItems has a constructor that takes such an object, so you can use this:
public class InvoiceItems : List<InvoiceItem>
{
public InvoiceItems(IEnumerable<InvoiceItem> items)
base(items){}
}
Then you can use:
InvoiceItems distinctItems = new InvoiceItems(aBunchOfInvoiceItems.Distinct());
As is though, I don't see much benefit in deriving from List<InvoiceItem> so I would probably lean more toward:
List<InvoiceItem> distinctItems = aBunchOfInvoiceItems.Distinct().ToList();
The error has everything to do with your class InvoiceItems, which inherits from List<InvoiceItem>.
Distinct returns an IEnumerable<InvoiceItem>: InvoiceItems is a very specific type of IEnumerable<InvoiceItem>, but any IEnumerable<InvoiceItem> is not necessarily an InvoiceItems.
One solution could be to use an implicit conversion operator, if that's what you wanted to do: Doh, totally forgot you can't convert to/from interfaces (thanks Saed)
public class InvoiceItems : List<InvoiceItem>
{
public InvoiceItems(IEnumerable<InvoiceItem> items) : base(items) { }
}
Other things to note:
Inheriting from List<T> is usually bad. Implement IList<T> instead.
Using a list throws away one of the big benefits of LINQ, which is lazy evaluation. Be sure that prefetching the results is actually what you want to do.
Aside from the custom class vs IEnumerable issue that the other answers deal with, there is one major problem with your code. Your class implements IEqualityComparer instead of IEquatable. When you use Distinct, the items being filtered must either implement IEquatable themselves, or you must use the overload that takes an IEqualityComparer parameter. As it stands now, your call to Distinct will not filter the items according to the IEqualityComparer Equals and GetHashCode methods you provided.
IEqualityComparer should be implemented by another class than the one being compared. If a class knows how to compare itself, like your InvoiceItem class, it should implement IEquatable.
Is there a way to use a collection of a generic class, without supplying the underlying type ?
Let's explain :
Here is what I'd like to have :
class TimeSerie<TValue> {
enter code here
}
List<TimeSerie<?>> blah;
Here is what I have to do so far :
class TimeSerie {}
class TypedTimeSerie<TValue> : TimeSerie {}
List<TimeSerie> blah;
So, any way to use the nice first solution ? (although I guess it would raise problems when trying to cast, for a loop for example ...)
You can make your using code generic too... but at some point you do have to specify the type argument. You're not going to be able to create an instance of the generic type without the type argument being known. You can provide that information at execution time using reflection if you must, but it has to be there somehow.
I dont see based on your question why you cannot derive your custom collection from ICollection<T> or List<T> (or maybe derive from ICollection and delegate the calls to a field of type List<T> you store internally?
(It's entirely possible I'm just not getting it, but can you give a small bit more sample code?)
Why not ?
List<TimeSerie<Object>> blah;
Then after you specify your object. Also define your base class accordingly.
Note that some 'mumbling' is possible in relation to anonymous types with c# thanks to two things:
Type inference
unification of identical anonymous types
If you are happy to rely on these two things remaining fixed (there are no guarantees on this, especially in relation to 2) then the following may be useful.
public static class Mumble
{
public static HashSet<T> HashSet<T>(T prototype)
{
return new HashSet<T>();
}
public static List<T> List<T>(T prototype)
{
return new List<T>();
}
}
You can use it like so:
var set = MumbleSet(new { Foo="", Bar="", Baz=0 });
var list = MumbleList(new { Foo="", Bar="", Baz=0 });
set.Add(new { Foo="x", Bar="y", Baz=1 });
set.Add(new { Foo="a", Bar="b", Baz=1 });
list.Add(new { Foo="a", Bar="b", Baz=1 });
var intersection = list.Intersect(set);
var concat = list.Concat(set);
This works well in cases where you have anonymous types you wish to populate into some other collection for use elsewhere within a method. A common use would be reading from a database query into a set for latter checking for existence within a loop where expressing this as a series of linq queries was either too cumbersome or too expensive.
For your motivating example you would have to add the following:
class TimeSerie<TValue>
{
// or some other constructor equivalent
public TimeSerie(TValue value) { /* assign the value */ }
}
static class TimeSerieMumble
{
public static TimeSerie<TValue> New<TValue>(TValue value)
{
return new TimeSerie<TValue>(value);
}
}
Then you could use the code like so:
var tsList = Mumble.List(TimeSerieMumble.New(new { Name="", Value=0 }));
foreach (var x in from c select new { c.Name, c.Value })
{
tsList.Add(TimeSerieMumble.New(new { x.Name, x.Value }));
}
Mumbling which 'leaks' into the public api is not feasible in c# 3.5 unless the type is to be mumbled through a series of type inferred generic methods in the same way as the above example. I have never seen a case where such a thing was useful given the resulting contortions required to the calling code. I would not think it would improve readability either. As a rule of thumb using more than the two levels of mumbling in the Name/Value example is likely to lead to serious complications down the line.
As others have said, there's no easy way to do this in C#.
However, if it's really important, it is possible to faithfully encode this pattern using a few extra types, although it's a bit ugly:
interface ITimeSeriesUser<X> {
X Use<T>(TimeSeries<T> series);
}
interface ITimeSeriesUser {
void Use<T>(TimeSeries<T> series);
}
interface ITimeSeries {
X Apply<X>(ITimeSeriesUser<X> user);
void Apply(ITimeSeriesUser user);
}
class TimeSeries<T> : ITimeSeries {
X Apply<X>(ITimeSeriesUser<X> user) { return user.Use(this); }
void Apply(ITimeSeriesUser user) { return user.Use(this); }
/* Your existing code goes here */
}
Now you can create a List<ITimeSeries> instance which holds TimeSeries<T>
values regardless of their type arguments, and you can use ITimeSeriesUser
implementations to manipulate them. Obviously this requires quite a bit of boilerplate,
but if you need a faithful way to express the concept of a TimeSeries<?> then this may be your best bet.
I have a class named "baseClass".
From this class I inherit a class names "inheritedClass" (public class inheritedClass: baseClass)
The baseClass contains a public function that returns a HashSet<baseClass>. When called from the inheritedClass, the return type is obviously still HashSet<baseClass>, but I need a HashSet<inheritedClass>.
A conversion ala (HashSet<inheritedClass>)returnValue, where returnValue is of Type HashSet<baseClass> doesn't work.
Is there a way to convert the HashSet-Type from baseClass to inheritedClass without converting each element manually?
Thanks in advance,
Frank
Do you really mean C# in the tags? HashMap is a Java type. Also it generally has two type parameters rather than one...
In C#, generic classes are always invariant. Some interfaces will be variant in C# 4, but very few (only those which either only use the type parameter in an output positiion, e.g. IEnumerable<T>, or only use the type parameter in an input position, e.g. IComparable<T>).
If you can provide more precise information about your situation, we'll probably be able to help come up with a simple solution - particularly if you can use LINQ with its Cast<T>() method.
EDIT: Okay, with HashSet<T>:
HashSet<BaseType> baseSet = ...;
var derivedSet = new HashSet<DerivedType>(baseSet.Cast<DerivedType>());
Note that even with C# 4 this would be necessary because the compiler doesn't know that every value in baseSet is an instance of DerivedType - there has to be an execution-time check. The reverse (creating a HashSet<BaseType> from a HashSet<DerivedType>) would work in C# 4.
FURTHER EDIT: If you just want to use UnionWith, that doesn't require a HashSet<DerivedType> - it requires an IEnumerable<DerivedType>. I suggest you do:
HashSet<BaseType> baseSet = ...;
HashSet<DerivedType> derivedSet = ...;
derivedSet.UnionWith(baseSet.Cast<DerivedType>());
Here's the solution
//**Your BaseClass**
public class BaseClass<T> where T : BaseClass<T>
{
public HashSet<T> GetHashSet()
{
HashSet<T> _hSet = new HashSet<T>();
//do some work
//create a HashSet<T> and return;
return _hSet;
}
}
//**Your Inherited/Derived Class**
public class InheritedClass : BaseClass<InheritedClass>
{
//you have the method inherited as you need.}
}