0

I don't get something, and if somebody can clarify:

I need to access this function / helper from here and there:

namespace Laf.Helpers
{
    public class Common
    {
        public string TimeSpanToString(TimeSpan val)
        {
            return val.ToString(@"hh\:mm");
        }
    }
}

And in my controller I access it by:

var tmp = new Common();
string str = tmp.TimeSpanToString(tp.DepartureTime);
transferPoint.Add(
    new ListTransferPointVM { PortName = tp.PortName, DepartureTime = str }
str);

And the question is how can I achieve and not have duplicate in every controller:

DepartureTime = TimeSpanToString(tp.DepartureTime)

Possible Answer I just found a way that compiler is not frowning on:

public class TransferController : Controller
{
    private Common common = new Common();

    public ActionResult Index ()
    {
      ...

and later, when I need it:

string time = common.TimeSpanToString((TimeSpan)variable);

1 Answer 1

4

You could make your method string TimeSpanToString(TimeSpan) a static method. This way you can access it without having to make a Common object. Your code will look as follows:

namespace Laf.Helpers
{
    public class Common
    {
        public static string TimeSpanToString(TimeSpan val)
        {
            return val.ToString(@"hh\:mm");
        }
    }
}

And your Controller:

transferPoint.Add(
    new ListTransferPointVM { 
        PortName = tp.PortName, 
        DepartureTime = Common.TimeSpanToString(tp.DepartureTime) }
    Common.TimeSpanToString(tp.DepartureTime));

EDIT: As suggested by Michael Petrotta an extension method would be better. An implementation could be:

namespace LaF.ExtensionMethods
{
    public static class MyExtensions
    {
        public static string TimeSpanToString(this TimeSpan ts)
        {
            return ts.ToString(@"hh\:mm");
        }
    }
}

You can now call the method like:

tp.DepartureTime.TimeSpanToString();

More on Extension Methods in C#

Sign up to request clarification or add additional context in comments.

3 Comments

An extension method would be even better.
To the TimeSpan class? I agree. I had not thought about that solution yet, thanks!
And I agree with MichaelPetrotta. That didn't came to mind to. And to @Simon: I was searching for months to achieve this and no luck. I have started to do more complex app and I need this, and... Didn't see tree from the forest :( Thanks a bunch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.