Why use generic constraints in C#

前端 未结 7 1697
日久生厌
日久生厌 2020-11-29 05:48

I\'ve read an excellent article on MSDN regarding Generics in C#.

The question that popped in my head was - why should i be using generic constraints?

For ex

相关标签:
7条回答
  • 2020-11-29 06:42

    This youtube video actually demonstrates the importance of generic constraints https://www.youtube.com/watch?v=GlqBRIgMgho.

    Now below goes a long textual answer.

    “Generic’s helps to decouple logic from the data type. So that we attach any data type with any logic for high reusability.”

    But many times some logic’s can be attached to only specific data types.

    public class CompareNumeric<UNNKOWDATATYPE>
    {
            public bool Compareme(UNNKOWDATATYPE v1, UNNKOWDATATYPE v2)
            {
                if (v1 > v2)
                {return true;}
                else
               {return false;}
            }
    }
    

    For example above is a simple generic class which does comparison if one number is greater than other number. Now the greater and less than comparison is very specific to numeric data types. These kind of comparison’s cannot be done on non-numeric types like string.

    So if some uses the classes with “int” type its perfectly valid.

    CompareNumeric<int> obj = new CompareNumeric<int>();
    bool boolgreater = obj.Compare(10,20);
    

    If someone uses it with “double” data type again perfectly valid.

    CompareNumeric<double> obj = new CompareNumeric<double>();
    bool boolgreater = obj.Compare(100.23,20.45);
    

    But using string data type with this logic will lead undesirable results. So we would like to restrict or put a constraint on what kind of types can be attached to a generic class this is achieved by using “generic constraints”.

    CompareNumeric<string> obj = new CompareNumeric<string>();
    bool boolgreater = obj.Compare(“interview”,”interviewer”);
    

    Generic type can be restricted by specifying data type using the “WHERE” keyword after the generic class as shown in the below code. Now if any client tries to attach “string” data type with the below class it will not allow, thus avoiding undesirable results.

    public class CompareNumeric<UNNKOWDATATYPE> where UNNKOWDATATYPE : int, double
    {
    
    }
    
    0 讨论(0)
提交回复
热议问题