I’m Learning C# – Part 11

In this lesson, we are going to use enum and switch together.

class Program
{
static void Main(string[] args)
{
List<doc> DocList = new List<doc>()
{
new doc {name =”first”, status = testStatus.Created, number= 1},
new doc {name =”second”, status = testStatus.Review, number= 2},
new doc {name =”third”, status = testStatus.Approval, number= 4},
new doc {name =”forth”, status = testStatus.Released, number= 4},
new doc {name =”fifth”, status = testStatus.Obsolete, number= 5},
};
foreach (var item in DocList)
{
switch (item.status)
{
case testStatus.Created:
Console.ForegroundColor = ConsoleColor.White;
break;
case testStatus.Review:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case testStatus.Approval:
Console.ForegroundColor = ConsoleColor.Cyan;
break;
case testStatus.Released:
Console.ForegroundColor = ConsoleColor.Green;
break;
case testStatus.Obsolete:
Console.ForegroundColor = ConsoleColor.Red;
break;
default:
break;
}
Console.WriteLine(“the name is {0} and status is {1}”, item.name, item.status);

}
Console.ReadLine();
}
}

class doc
{
public string name {get; set;}
public testStatus status {get; set;}
public int number {get; set;}
}

public enum testStatus
{
Created,
Review,
Approval,
Released,
Obsolete
}

Enum is used when we want to restrict the values that a particular parameter can take. In this case, we want to limit the status to Created, Review, Approval, Released or Obsolete.

The switch, depending on the status, changes the ForegroundColour of the console as can be seen in the output below:

capture

Isn’t that lovely 🙂

What if we encounter an exception during run time?

In that instance, we make use of the try catch block.

try
{
var content = File.ReadAllText(@”C:\google.txt”);
Console.WriteLine(content);
}
catch(FileNotFoundException e)
{
Console.Write(e.Message);
}
Console.ReadLine();

With this post, I am pretty much wrapping up the C# sessions.

Do comment on areas I haven’t covered and maybe I will write another post 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s