0

I'm trying to expand System.TimeSpan in C# because I need a extra method to convert the GameTime to a TimeSpan. This is what i tried:

class TimeSpanner : TimeSpan
{
}

apperently it's not possible to extend the Timespan struct. Does anyone know why it can't be extended? And how do I properly make this work?

Steve Van Opstal
  • 1,062
  • 1
  • 9
  • 27

4 Answers4

2

You're taking completely the wrong approach. GameTime has member properties ElapsedGameTime and TotalGameTime that provide the two different TimeSpans that make up a GameTime object. Use them like this:

protected override void Update(GameTime gameTime)
{
    TimeSpan elapsed = gameTime.ElapsedGameTime;
    TimeSpan total = gameTime.TotalGameTime;

    // Personally, I just do this:
    float seconds = (float)gameTime.ElapsedGameTime.TotalSeconds;

    // ...
}
Andrew Russell
  • 26,924
  • 7
  • 58
  • 104
1

You can not inherit from a struct.

Form MSDN on structs:

There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do.

As an alternative to what you are trying, consider using extension methods.

InBetween
  • 32,319
  • 3
  • 50
  • 90
1

A TimeSpan is a struct and structs (which are a value type) cannot be subclassed. You should probably investigate using an operator to perform a conversion.

You could do something like this:

public static implicit operator TimeSpan(GameTime gt) 
{
    return gt.GetTimeSpan();
}

You could then use this like this:

TimeSpan timeSpan = (TimeSpan)myGameTime;
CodingGorilla
  • 19,612
  • 4
  • 45
  • 65
1

If you need an extra method to do a conversion then why not just make an extension method then?

public static void DoStuff(this TimeSpan timeSpan, GameTime gameTime)
{
     ...
}
Scott
  • 999
  • 7
  • 13