Sum of Timespan in C#?

Asked

Viewed 675 times

12

In the sum of two variables of the type Timespan with the language I was able to observe that it happens as if it were a mathematical operation of two simple numbers, example:

TimeSpan t1 = TimeSpan.ParseExact("00:01:45", "c", CultureInfo.InvariantCulture);
TimeSpan t2 = TimeSpan.ParseExact("00:02:45", "c", CultureInfo.InvariantCulture);

TimeSpan t3 = t1 + t2;

and the end result of this are 4 minutes and 30 seconds in the variable t3.

Two structures should theoretically not do sum operations transparently, I would like to know the following:

  • How this sum operation of the two structures works Timespan?
  • This can be done in other classes, as a way to facilitate mathematical or conversion operations, there is examples to demonstrate?
  • 1

    Knowing that you know the subject, is there any specific one you wish to know? What is there is correct. That is, what do you mean by "How does this operation work"? What other classes for example? With some certainly, with others not? Or it could, it depends on the definition of what you want to do. For example, there is no DateTime one Add(DateTime) and it wasn’t forgetfulness. So at this time I’m finding it not clear or broad, but I know you can improve.

  • It has no specifics, I spoke generally. How this operation works in the broad sense of architecture features .net proper, not to restrict only TimeSpan, but, yes if I can do it in other classes and structures. @bigown. It’s a general answer. Yes I know the subject and have no question about it specifically.

  • I understood then, then I see if I can answer and if you need since you have two answers that can be good, I’ll read later.

  • Perhaps with examples of cast @bigown would be a differential!

2 answers

11


How this sum operation of the two Timespan structures works?

This works because C# allows operator overload, defining static methods using the keyword operador.

To overload an operator it is necessary to create in the class a static method named with the operator symbol being overloaded.
For unary operators the method declares a parameter in the case of binary operators two parameters.
The parameter(s) (s) shall (m) be of the same type as the class/structure declaring the operator.

In the case of Timespan method that’s how it is:

public static TimeSpan operator +(TimeSpan t1, TimeSpan t2) 
{
    return t1.Add(t2);
}

Out of curiosity the method add() that’s how it is:

public TimeSpan Add(TimeSpan ts) {
    long result = _ticks + ts._ticks;
    // Overflow if signs of operands was identical and result's
    // sign was opposite.
    // >> 63 gives the sign bit (either 64 1's or 64 0's).
    if ((_ticks >> 63 == ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
        throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
    return new TimeSpan(result);
}

This can be done in other classes, as a way to facilitate mathematical or conversion operations, there are examples to demonstrate?

Yes, this can be applied to any structure/class, just needs to overload the operators you want to make available.

Example of operator overload + in a structure representing a complex number.

public struct Complex 
{
   public int real;
   public int imaginary;

   public Complex(int real, int imaginary) 
   {
      this.real = real;
      this.imaginary = imaginary;
   }

   public static Complex operator +(Complex c1, Complex c2) 
   {
      return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
   }
}

With regard to conversions, it is possible to declare them implicitly or explicitly.

Example of a type conversion operator to allow implicit conversion (without using cast) of that kind in another.

class Digit
{
    public Digit(double d) { val = d; }
    public double val;

    // Conversão de Digit to double
    public static implicit operator double(Digit d)
    {
        return d.val;
    }
    //  Conversão de double para Digit
    public static implicit operator Digit(double d)
    {
        return new Digit(d);
    }
}

Example of use:

Digit dig = new Digit(7);
//Conversão implícita de Digit para double
double num = dig;
//Conversão implícita de double para Digit
Digit dig2 = 12;

Example use of a type conversion operator to allow explicit conversion (invoked using cast) of that kind in another.

class Celsius
{
    public Celsius(float temp)
    {
        degrees = temp;
    }
    public static explicit operator Fahrenheit(Celsius c)
    {
        return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);
    }
    public float Degrees
    {
        get { return degrees; }
    }
    private float degrees;
}

Example of use:

Fahrenheit fahr = new Fahrenheit(100.0f);
//Conversão explicita de Fahrenheit para Celsius
Celsius c = (Celsius)fahr;

8

The sum between the two structures works because the language allows to do operator overload.

How this sum operation of the two Timespan structures works?

This is defined in the creation of the structure, in the same way that fields are defined, the constructor, etc. It is a static method with any return type that contains the reserved word operator.

Something like:

public static TimeSpan operator +(TimeSpan c1, TimeSpan c2) 
{
    // fazer a operação 
    return timeSpan;
}

This can be done in other classes, as a way to facilitate mathematical or conversion operations, there are examples to demonstrate?

Yes. There are some, basically you can do anything. A basic example a structure that represents two-dimensional vectors.

I defined a method for summing two vectors, overloading the operator + and a conversion of int for Vector - this conversion is called User-Defined Conversion.

struct Vector
{
    public int ComponenteX;
    public int ComponenteY;

    public Vector(int cX, int cY){
        ComponenteX = cX;
        ComponenteY = cY;
    }

    public static Vector operator +(Vector v1, Vector v2) 
    {
        return new Vector(v1.ComponenteX + v2.ComponenteX, v1.ComponenteY + v2.ComponenteY);
    }

    public static implicit operator Vector(int componenteX)
    {
        return new Vector(componenteX, 0);
    }

    public override string ToString()
    {
        return $"{ComponenteX}, {ComponenteY}";
    }
}

See working on . NET Fiddle.

  • I was going to suggest just that :)

  • First thing that popped into my head was vector, I don’t know why XD

Browser other questions tagged

You are not signed in. Login or sign up in order to post.