posted
I'm having a problem with the 'is' statement in c#, and I was hoping that someone here would know the answer.
I have a class which implements the IComparable interface. I have a generic function in another class that checks to see if the type is several different interfaces. It picks up ICloneable, but for some reason it is not getting the IComparable. Does anyone know why?
code:
public class Edge<LabelType> : IComparable, IComparable<Edge<LabelType>>, ICloneable
code:
if (!((typeof(T) is IComparable) && (typeof(T) is ICloneable)))
like I said, is is getting the ICloneable right, but (typeof(T) is IComparable) keeps evaluating as false.
posted
leave off typeof. I don't use C#, but this looks exactly like instanceof in java.
If so, then IComparable works because types are comparable, but ICloneable fails because types aren't cloneable. The object itself is IComparable and ICloneable, though, so if you write T is ICloneable, it should work.
A quick google supports this view.
Posts: 15770 | Registered: Dec 2001
| IP: Logged |
posted
T is the type, rather than a variable. Is there a better way to check whether the type T is IComparable, because trying to go without the typeof()'s gives me a compiler error.
Edit:
actually, it looks like 'is' isn't going to get me what I want. Is there some other way to make sure that this class can only be used with types that support IComparable?
Edit again:
Nevermind. It looks like what I really wanted was to use constraints in the class declaration. The problem is solved now, I think. Thanks for your help.
Posts: 2437 | Registered: Apr 2005
| IP: Logged |
There might be a way to do it more directly, but getting the list of interfaces then seeing if the given interface is a member is a good way to go.
Btw, there's almost always a better way to do things than checking types. Could you post a larger sample of your code? That might enable some suggestions about how to improve the structure of your program.
edit: and you already found the better way while I was typing Good. No need to delete, btw.
Posts: 15770 | Registered: Dec 2001
| IP: Logged |
posted
I don't understand why you would delete this thread. There might be someone else who has this exact problem in a few days, or someone else could use this thread to post another question about c#.
Posts: 1658 | Registered: Sep 2003
| IP: Logged |
posted
C# major is the key with the most sharps (7) in the key signature. C# minor (4 sharps) was Chopin's favorite key to compose in (note--not the enharmonic key of D-flat).
The frequency of the C# above middle C is 277.183 Hz.
To people with perfect pitch, C# is often described as one of the "brightest" pitches.
Posts: 1314 | Registered: Jan 2006
| IP: Logged |