Williamq

Hi

Anyone know how to cast an object to generic interface

Like IComparable interface, I can do

Code Snippet

object thisObject = typeField.GetValue();

IComparable iComparableThis = thisObject as IComparable;

How to do it for generic interface

Code Snippet

object thisObject = typeField.GetValue();

IEquatable<T> iEquatableThis = thisObject as IEquatable<T>;

Thanks!




Re: .NET Base Class Library How to cast object to generic interface?

Williamq

What i am trying to do is comparing all fields in the class. If the field type is value, Equality operator (==) or Object.Equals method will do the job. But if the field type is reference, Object.Equals just do the ReferenceEquals check unless you override the equals method in the class.

Should I totally forget about the IEquatable<T> interface and just override the equals method






Re: .NET Base Class Library How to cast object to generic interface?

Inbar Gazit - MSFT

You can cast to a generic interface only if you either have an instance of T (like IFoo<Bar>) or if you want to use T you need this to reside inside another generic class or method.

So if this is ClassBar<T> .... { ...} you can inside it cast to IFoo<T>.

Same thing if it's a MethodBar<T> (....) {...} you can do the same. The comipler has to know what T is.






Re: .NET Base Class Library How to cast object to generic interface?

Williamq

Thanks.

So overriding Equals method is the only way to do it






Re: .NET Base Class Library How to cast object to generic interface?

Inbar Gazit - MSFT

No, you can still create your own MyComparer<T> class that implements Equals() method and use T inside this method. You can then use this Comparer instead of the default one.




Re: .NET Base Class Library How to cast object to generic interface?

Williamq

Thank you. But in my case, I may never know what T is as I use reflection to get all fields and use

object thisObject = typeField.GetValue(); to compare value/object.