Can I call ONLY those methods supported on System.Object type , if I use generic?? : yes because when you want to do operation on generic (data) type it can only identify it as a object base class (because everything in .net is inherited from Object) and hence you can only call methods which can be called on Object.
if you want to make your generic more specific you can use constraints by which you can only use that particular generic for the constraint define and hence can call any method that is supported by constraint let say you define a generic class list where T: IComparable. So here compiler allow only IComparable type to use the generic class and since you know all types that can use the class will be of Icomparable so you can call function defined in Icomparable like T.CompareTo(obj)
Cannot use the + operator or the > operator. (Why ???? ): because if i assume that my generics can be used by any type then it will be difficult for compiler to call + operator on some "Person" type or for that matter any type which can't support addition, The reason is that the less-than or + operator in C# only works with certain types. Hence will be error on runtime
See how constraints helps to overcome this issue better explanation on this article of MSDN Magazine
http://msdn.microsoft.com/en-us/magazine/cc164081.aspx
Ref: http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/c74f0b06-31b4-438a-b0be-8fbed288b1e9
if you want to make your generic more specific you can use constraints by which you can only use that particular generic for the constraint define and hence can call any method that is supported by constraint let say you define a generic class list
Cannot use the + operator or the > operator. (Why ???? ): because if i assume that my generics can be used by any type then it will be difficult for compiler to call + operator on some "Person" type or for that matter any type which can't support addition, The reason is that the less-than or + operator in C# only works with certain types. Hence will be error on runtime
See how constraints helps to overcome this issue better explanation on this article of MSDN Magazine
http://msdn.microsoft.com/en-us/magazine/cc164081.aspx
Ref: http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/c74f0b06-31b4-438a-b0be-8fbed288b1e9
No comments:
Post a Comment