Stopwatch exercise from training course The 2019 Stack Overflow Developer Survey Results Are InIs this Agent/Actor implementation issue free?Rolling my own Configuration with UIObject manager classLinq-to-Sage: CRUD OperationsFootball game using factory and command patternsUsing pointers and type cast to break up integers into byte array3-axis coordinate system for a Chinese Checkers boardSimple Unity IntegrationStopwatch exception implementation in C#Stopwatch class

Is it correct to say the Neural Networks are an alternative way of performing Maximum Likelihood Estimation? if not, why?

Can a flute soloist sit?

Can withdrawing asylum be illegal?

Is it safe to harvest rainwater that fell on solar panels?

Output the Arecibo Message

Why can't devices on different VLANs, but on the same subnet, communicate?

Button changing its text & action. Good or terrible?

What does Linus Torvalds mean when he says that Git "never ever" tracks a file?

I am an eight letter word. What am I?

Deal with toxic manager when you can't quit

What's the name of these plastic connectors

What is the most efficient way to store a numeric range?

How to charge AirPods to keep battery healthy?

Did Scotland spend $250,000 for the slogan "Welcome to Scotland"?

The phrase "to the numbers born"?

What information about me do stores get via my credit card?

Why couldn't they take pictures of a closer black hole?

writing variables above the numbers in tikz picture

Is it ok to offer lower paid work as a trial period before negotiating for a full-time job?

APIPA and LAN Broadcast Domain

Why isn't the black hole white?

Can a rogue use sneak attack with weapons that have the thrown property even if they are not thrown?

For what reasons would an animal species NOT cross a *horizontal* land bridge?

Why didn't the Event Horizon Telescope team mention Sagittarius A*?



Stopwatch exercise from training course



The 2019 Stack Overflow Developer Survey Results Are InIs this Agent/Actor implementation issue free?Rolling my own Configuration with UIObject manager classLinq-to-Sage: CRUD OperationsFootball game using factory and command patternsUsing pointers and type cast to break up integers into byte array3-axis coordinate system for a Chinese Checkers boardSimple Unity IntegrationStopwatch exception implementation in C#Stopwatch class



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2












$begingroup$


I'm currently undertaking a training course to try & further develop my skills in C#. The latest exercise was to create a basic stopwatch class that meets the following criteria -




Design a class called Stopwatch. The job of this class is to simulate
a stopwatch. It should provide two methods: Start and Stop. We call
the start method first, and the stop method next. Then we ask the
stopwatch about the duration between start and stop. Duration should
be a value in TimeSpan. Display the duration on the console. We should
also be able to use a stopwatch multiple times. So we may start and
stop it and then start and stop it again. Make sure the duration value
each time is calculated properly. We should not be able to start a
stopwatch twice in a row (because that may overwrite the initial start
time). So the class should throw an InvalidOperationException if its
started twice.



Educational tip: The aim of this exercise is to make you understand
that a class should be always in a valid state. We use encapsulation
and information hiding to achieve that. The class should not reveal
its implementation detail. It only reveals a little bit, like a
blackbox. From the outside, you should not be able to misuse a class
because you shouldn’t be able to see the implementation detail.




I'm sure someone is bound to mention it, but yes I'm aware that there is already a stopwatch class in the .NET framework, but as this was the exercise I wanted to try & accomplish it based on the requirements.



The class is as follows -



public class Stopwatch

private TimeSpan _duration;
private TimeSpan _start;

public Stopwatch()

ZeroStart();


public void Start()

if (_start != TimeSpan.Zero)
throw new InvalidOperationException("The stopwatch has already been started.");

_start = DateTime.Now.TimeOfDay;


public TimeSpan Stop()

if (_start == TimeSpan.Zero)
throw new InvalidOperationException("The stopwatch has not been started.");

_duration = DateTime.Now.TimeOfDay - _start;
ZeroStart();
return _duration;


private void ZeroStart()

_start = TimeSpan.Zero;




I haven't done an awful lot of OOP or even effective work with classes. Most of the stuff I have done in the past has been more procedural based stuff, just a long list of static methods in static classes etc...



I'm not sure if this is really enough to go on for anyone to actually critique me on so I'm sorry if that's the case.



I've tested the code using the following -



class Program

static void Main(string[] args)

UsingStopwatch();


static void UsingStopwatch()

Console.WriteLine("This is a stop watch. Type 'start' to start it & 'stop' to stop it.");
var stopwatch = new Stopwatch();

while (true)

var input = Console.ReadLine();

switch (input.ToLower())

case "start":
stopwatch.Start();
break;
case "stop":
Console.WriteLine(stopwatch.Stop());
break;
default:
Console.WriteLine("Sorry I don't recognize that.");
break;













share|improve this question









New contributor




Webbarr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$











  • $begingroup$
    Using TimeOfDay is not is good idea if you want to use the stop watch from one day to the next ;). i.e: new DateTime(2019, 01, 02, 00, 05, 00).TimeOfDay - new DateTime(2019, 01, 01, 23, 55, 00).TimeOfDay -> -23:50:00. You can just use DateTime instead.
    $endgroup$
    – JanDotNet
    2 hours ago











  • $begingroup$
    Sorry if this sounds stupid but if I change it to _start = DateTime; or _start = new DateTime; both throw exceptions. The former being because DateTime is a type & the latter being that DateTime can't be converted to TimeSpan. How exactly do you mean to just use DateTime?
    $endgroup$
    – Webbarr
    2 hours ago

















2












$begingroup$


I'm currently undertaking a training course to try & further develop my skills in C#. The latest exercise was to create a basic stopwatch class that meets the following criteria -




Design a class called Stopwatch. The job of this class is to simulate
a stopwatch. It should provide two methods: Start and Stop. We call
the start method first, and the stop method next. Then we ask the
stopwatch about the duration between start and stop. Duration should
be a value in TimeSpan. Display the duration on the console. We should
also be able to use a stopwatch multiple times. So we may start and
stop it and then start and stop it again. Make sure the duration value
each time is calculated properly. We should not be able to start a
stopwatch twice in a row (because that may overwrite the initial start
time). So the class should throw an InvalidOperationException if its
started twice.



Educational tip: The aim of this exercise is to make you understand
that a class should be always in a valid state. We use encapsulation
and information hiding to achieve that. The class should not reveal
its implementation detail. It only reveals a little bit, like a
blackbox. From the outside, you should not be able to misuse a class
because you shouldn’t be able to see the implementation detail.




I'm sure someone is bound to mention it, but yes I'm aware that there is already a stopwatch class in the .NET framework, but as this was the exercise I wanted to try & accomplish it based on the requirements.



The class is as follows -



public class Stopwatch

private TimeSpan _duration;
private TimeSpan _start;

public Stopwatch()

ZeroStart();


public void Start()

if (_start != TimeSpan.Zero)
throw new InvalidOperationException("The stopwatch has already been started.");

_start = DateTime.Now.TimeOfDay;


public TimeSpan Stop()

if (_start == TimeSpan.Zero)
throw new InvalidOperationException("The stopwatch has not been started.");

_duration = DateTime.Now.TimeOfDay - _start;
ZeroStart();
return _duration;


private void ZeroStart()

_start = TimeSpan.Zero;




I haven't done an awful lot of OOP or even effective work with classes. Most of the stuff I have done in the past has been more procedural based stuff, just a long list of static methods in static classes etc...



I'm not sure if this is really enough to go on for anyone to actually critique me on so I'm sorry if that's the case.



I've tested the code using the following -



class Program

static void Main(string[] args)

UsingStopwatch();


static void UsingStopwatch()

Console.WriteLine("This is a stop watch. Type 'start' to start it & 'stop' to stop it.");
var stopwatch = new Stopwatch();

while (true)

var input = Console.ReadLine();

switch (input.ToLower())

case "start":
stopwatch.Start();
break;
case "stop":
Console.WriteLine(stopwatch.Stop());
break;
default:
Console.WriteLine("Sorry I don't recognize that.");
break;













share|improve this question









New contributor




Webbarr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$











  • $begingroup$
    Using TimeOfDay is not is good idea if you want to use the stop watch from one day to the next ;). i.e: new DateTime(2019, 01, 02, 00, 05, 00).TimeOfDay - new DateTime(2019, 01, 01, 23, 55, 00).TimeOfDay -> -23:50:00. You can just use DateTime instead.
    $endgroup$
    – JanDotNet
    2 hours ago











  • $begingroup$
    Sorry if this sounds stupid but if I change it to _start = DateTime; or _start = new DateTime; both throw exceptions. The former being because DateTime is a type & the latter being that DateTime can't be converted to TimeSpan. How exactly do you mean to just use DateTime?
    $endgroup$
    – Webbarr
    2 hours ago













2












2








2





$begingroup$


I'm currently undertaking a training course to try & further develop my skills in C#. The latest exercise was to create a basic stopwatch class that meets the following criteria -




Design a class called Stopwatch. The job of this class is to simulate
a stopwatch. It should provide two methods: Start and Stop. We call
the start method first, and the stop method next. Then we ask the
stopwatch about the duration between start and stop. Duration should
be a value in TimeSpan. Display the duration on the console. We should
also be able to use a stopwatch multiple times. So we may start and
stop it and then start and stop it again. Make sure the duration value
each time is calculated properly. We should not be able to start a
stopwatch twice in a row (because that may overwrite the initial start
time). So the class should throw an InvalidOperationException if its
started twice.



Educational tip: The aim of this exercise is to make you understand
that a class should be always in a valid state. We use encapsulation
and information hiding to achieve that. The class should not reveal
its implementation detail. It only reveals a little bit, like a
blackbox. From the outside, you should not be able to misuse a class
because you shouldn’t be able to see the implementation detail.




I'm sure someone is bound to mention it, but yes I'm aware that there is already a stopwatch class in the .NET framework, but as this was the exercise I wanted to try & accomplish it based on the requirements.



The class is as follows -



public class Stopwatch

private TimeSpan _duration;
private TimeSpan _start;

public Stopwatch()

ZeroStart();


public void Start()

if (_start != TimeSpan.Zero)
throw new InvalidOperationException("The stopwatch has already been started.");

_start = DateTime.Now.TimeOfDay;


public TimeSpan Stop()

if (_start == TimeSpan.Zero)
throw new InvalidOperationException("The stopwatch has not been started.");

_duration = DateTime.Now.TimeOfDay - _start;
ZeroStart();
return _duration;


private void ZeroStart()

_start = TimeSpan.Zero;




I haven't done an awful lot of OOP or even effective work with classes. Most of the stuff I have done in the past has been more procedural based stuff, just a long list of static methods in static classes etc...



I'm not sure if this is really enough to go on for anyone to actually critique me on so I'm sorry if that's the case.



I've tested the code using the following -



class Program

static void Main(string[] args)

UsingStopwatch();


static void UsingStopwatch()

Console.WriteLine("This is a stop watch. Type 'start' to start it & 'stop' to stop it.");
var stopwatch = new Stopwatch();

while (true)

var input = Console.ReadLine();

switch (input.ToLower())

case "start":
stopwatch.Start();
break;
case "stop":
Console.WriteLine(stopwatch.Stop());
break;
default:
Console.WriteLine("Sorry I don't recognize that.");
break;













share|improve this question









New contributor




Webbarr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




I'm currently undertaking a training course to try & further develop my skills in C#. The latest exercise was to create a basic stopwatch class that meets the following criteria -




Design a class called Stopwatch. The job of this class is to simulate
a stopwatch. It should provide two methods: Start and Stop. We call
the start method first, and the stop method next. Then we ask the
stopwatch about the duration between start and stop. Duration should
be a value in TimeSpan. Display the duration on the console. We should
also be able to use a stopwatch multiple times. So we may start and
stop it and then start and stop it again. Make sure the duration value
each time is calculated properly. We should not be able to start a
stopwatch twice in a row (because that may overwrite the initial start
time). So the class should throw an InvalidOperationException if its
started twice.



Educational tip: The aim of this exercise is to make you understand
that a class should be always in a valid state. We use encapsulation
and information hiding to achieve that. The class should not reveal
its implementation detail. It only reveals a little bit, like a
blackbox. From the outside, you should not be able to misuse a class
because you shouldn’t be able to see the implementation detail.




I'm sure someone is bound to mention it, but yes I'm aware that there is already a stopwatch class in the .NET framework, but as this was the exercise I wanted to try & accomplish it based on the requirements.



The class is as follows -



public class Stopwatch

private TimeSpan _duration;
private TimeSpan _start;

public Stopwatch()

ZeroStart();


public void Start()

if (_start != TimeSpan.Zero)
throw new InvalidOperationException("The stopwatch has already been started.");

_start = DateTime.Now.TimeOfDay;


public TimeSpan Stop()

if (_start == TimeSpan.Zero)
throw new InvalidOperationException("The stopwatch has not been started.");

_duration = DateTime.Now.TimeOfDay - _start;
ZeroStart();
return _duration;


private void ZeroStart()

_start = TimeSpan.Zero;




I haven't done an awful lot of OOP or even effective work with classes. Most of the stuff I have done in the past has been more procedural based stuff, just a long list of static methods in static classes etc...



I'm not sure if this is really enough to go on for anyone to actually critique me on so I'm sorry if that's the case.



I've tested the code using the following -



class Program

static void Main(string[] args)

UsingStopwatch();


static void UsingStopwatch()

Console.WriteLine("This is a stop watch. Type 'start' to start it & 'stop' to stop it.");
var stopwatch = new Stopwatch();

while (true)

var input = Console.ReadLine();

switch (input.ToLower())

case "start":
stopwatch.Start();
break;
case "stop":
Console.WriteLine(stopwatch.Stop());
break;
default:
Console.WriteLine("Sorry I don't recognize that.");
break;










c# object-oriented programming-challenge






share|improve this question









New contributor




Webbarr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Webbarr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 2 hours ago







Webbarr













New contributor




Webbarr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 3 hours ago









WebbarrWebbarr

112




112




New contributor




Webbarr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Webbarr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Webbarr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











  • $begingroup$
    Using TimeOfDay is not is good idea if you want to use the stop watch from one day to the next ;). i.e: new DateTime(2019, 01, 02, 00, 05, 00).TimeOfDay - new DateTime(2019, 01, 01, 23, 55, 00).TimeOfDay -> -23:50:00. You can just use DateTime instead.
    $endgroup$
    – JanDotNet
    2 hours ago











  • $begingroup$
    Sorry if this sounds stupid but if I change it to _start = DateTime; or _start = new DateTime; both throw exceptions. The former being because DateTime is a type & the latter being that DateTime can't be converted to TimeSpan. How exactly do you mean to just use DateTime?
    $endgroup$
    – Webbarr
    2 hours ago
















  • $begingroup$
    Using TimeOfDay is not is good idea if you want to use the stop watch from one day to the next ;). i.e: new DateTime(2019, 01, 02, 00, 05, 00).TimeOfDay - new DateTime(2019, 01, 01, 23, 55, 00).TimeOfDay -> -23:50:00. You can just use DateTime instead.
    $endgroup$
    – JanDotNet
    2 hours ago











  • $begingroup$
    Sorry if this sounds stupid but if I change it to _start = DateTime; or _start = new DateTime; both throw exceptions. The former being because DateTime is a type & the latter being that DateTime can't be converted to TimeSpan. How exactly do you mean to just use DateTime?
    $endgroup$
    – Webbarr
    2 hours ago















$begingroup$
Using TimeOfDay is not is good idea if you want to use the stop watch from one day to the next ;). i.e: new DateTime(2019, 01, 02, 00, 05, 00).TimeOfDay - new DateTime(2019, 01, 01, 23, 55, 00).TimeOfDay -> -23:50:00. You can just use DateTime instead.
$endgroup$
– JanDotNet
2 hours ago





$begingroup$
Using TimeOfDay is not is good idea if you want to use the stop watch from one day to the next ;). i.e: new DateTime(2019, 01, 02, 00, 05, 00).TimeOfDay - new DateTime(2019, 01, 01, 23, 55, 00).TimeOfDay -> -23:50:00. You can just use DateTime instead.
$endgroup$
– JanDotNet
2 hours ago













$begingroup$
Sorry if this sounds stupid but if I change it to _start = DateTime; or _start = new DateTime; both throw exceptions. The former being because DateTime is a type & the latter being that DateTime can't be converted to TimeSpan. How exactly do you mean to just use DateTime?
$endgroup$
– Webbarr
2 hours ago




$begingroup$
Sorry if this sounds stupid but if I change it to _start = DateTime; or _start = new DateTime; both throw exceptions. The former being because DateTime is a type & the latter being that DateTime can't be converted to TimeSpan. How exactly do you mean to just use DateTime?
$endgroup$
– Webbarr
2 hours ago










0






active

oldest

votes












Your Answer





StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");

StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);






Webbarr is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217285%2fstopwatch-exercise-from-training-course%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes








Webbarr is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















Webbarr is a new contributor. Be nice, and check out our Code of Conduct.












Webbarr is a new contributor. Be nice, and check out our Code of Conduct.











Webbarr is a new contributor. Be nice, and check out our Code of Conduct.














Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217285%2fstopwatch-exercise-from-training-course%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

格濟夫卡 參考資料 导航菜单51°3′40″N 34°2′21″E / 51.06111°N 34.03917°E / 51.06111; 34.03917ГезівкаПогода в селі 编辑或修订