Maha

Maha

  • NA
  • 0
  • 324.8k

Switch and Enum

Jul 3 2013 9:40 AM
This program is given in the following website
http://www.dotnetperls.com/switch-enum

Its output is
False
True

If this program is altered like as follows

Instead of Priority priority = Priority.Zero; is replaced with new a code Priority priority = new Priority();

priority = Priority.Low; and priority = Priority.Important; command out

The output is
False
False

Please explain the reason.

Program

using System;

enum Priority
{
Zero,
Low,
Medium,
Important,
Critical
};

class Program
{
static void Main()
{
// New local variable of the Priority enum type.
Priority priority = Priority.Zero;

//Set priority to critical on Monday.
if (DateTime.Today.DayOfWeek == DayOfWeek.Monday)
{
priority = Priority.Critical;
}

// Write this if the priority is important.
if (IsImportant(priority))
{
Console.WriteLine("The problem is important.");
}

// See if Low priority is important.
priority = Priority.Low;
Console.WriteLine(IsImportant(priority));

// See if Important priority is.
priority = Priority.Important;
Console.WriteLine(IsImportant(priority));

Console.ReadKey();
}

static bool IsImportant(Priority priority)
{
// Switch on the Priority enum.
switch (priority)
{
case Priority.Low:
case Priority.Medium:
case Priority.Zero:
default:
return false;
case Priority.Important:
case Priority.Critical:
return true;
}
}
}
/*
False
True
*/

Altered program

using System;

enum Priority
{
Zero,
Low,
Medium,
Important,
Critical
};

class Program
{
static void Main()
{
// New local variable of the Priority enum type.
//Priority priority = Priority.Zero;
Priority priority = new Priority();


//Set priority to critical on Monday.
if (DateTime.Today.DayOfWeek == DayOfWeek.Monday)
{
priority = Priority.Critical;
}

// Write this if the priority is important.
if (IsImportant(priority))
{
Console.WriteLine("The problem is important.");
}

// See if Low priority is important.
//priority = Priority.Low;
Console.WriteLine(IsImportant(priority));

// See if Important priority is.
//priority = Priority.Important;
Console.WriteLine(IsImportant(priority));

Console.ReadKey();
}

static bool IsImportant(Priority priority)
{
// Switch on the Priority enum.
switch (priority)
{
case Priority.Low:
case Priority.Medium:
case Priority.Zero:
default:
return false;
case Priority.Important:
case Priority.Critical:
return true;
}
}
}
/*
False
False
*/


Answers (2)