Question

This Code is Getting Error at line 11 and 13,Error Message is Error "Operator '<' cannot be applied to operands of type 'T' and 'int'" How can I check Values and print it in other way

class absval<T>
{
    private T _no;
    public void storeval(T x)
    {
        this._no = x;
    }
    public T getval()
    {
        if(this._no<0)
        {
        return (this._no*-1);
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        absval<int> a1 = new absval<int>();
        absval<double> a2 = new absval<double>();
        a1.storeval(-20);
        a2.storeval(-20.4);
        Console.WriteLine("{0}  {1}",a1.getval(),a2.getval());
        Console.ReadLine();
    }
}

thanks in advance

Was it helpful?

Solution

As long as you're not in danger of conversion errors with high precision numbers, you could use the numbers IConvertible implementation to get a generic approach. It looks cleaner than implementing a lot if and elses, although the former would probably be more efficient on micro level.

    public T getval()
    {
        if(_no is IConvertible) //could also be put in the generic constraint for <T>
        {
            //use decimal for the largest precision, 
            var dec = Convert.ToDecimal(_no); //will throw an exception if not numeric
            if (dec < 0) 
            {
                return (T)Convert.ChangeType(-dec, typeof(T));
            }
        }
        return _no;        
    }

OTHER TIPS

Well, _no is of type T where T is not constrained in any sense, so it can be a string, a Button or a double.

The compiler does not know how you are using the class, and it cannot guarantee that the line _no < 0 will make sense for the actual type put in the T (e.g., what should "Hello" < 0 do?), so it issues a compile error.

That said, C# does not have a generic constraint to a numeric type, so there is no simple way to do what you want to do (make a single absval method for all numeric types). Even if you look at the implementation of the static Math.Abs method, you will see that it has specific overloads for each and every one of the numeric types.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top