Consider the following C# code that parses a string into an enum value. What will be printed?
using System; enum Color { Red, Green, Blue } class Program { static void Main() { string input = "Green"; if (Enum.TryParse<Color>(input, out var color)) { Console.WriteLine((int)color); } else { Console.WriteLine("Parse failed"); } } }
Remember that enum values start at 0 by default and increment by 1.
The enum Color has Red=0, Green=1, Blue=2. Parsing "Green" succeeds and returns the enum value with underlying int 1.
What will happen when running this code?
using System; enum Status { Active, Inactive } class Program { static void Main() { string input = "Pending"; var status = (Status)Enum.Parse(typeof(Status), input); Console.WriteLine(status); } }
Enum.Parse throws an exception if the string does not match any enum name.
Since "Pending" is not a member of the Status enum, Enum.Parse throws an ArgumentException.
Look at this code snippet. It tries to parse a string to an enum but always fails. Why?
using System; enum Direction { North, South, East, West } class Program { static void Main() { string input = "north"; if (Enum.TryParse<Direction>(input, out var dir)) { Console.WriteLine(dir); } else { Console.WriteLine("Failed to parse"); } } }
TryParse can be case-insensitive if you specify an option.
By default, Enum.TryParse is case-insensitive. The string "north" does not match the enum member "North" because of case difference.
Choose the code snippet that correctly parses the string "west" to the enum Direction ignoring case.
enum Direction { North, South, East, West }Look for the overload of TryParse that accepts a boolean for case-insensitivity.
Option D uses Enum.TryParse with the third parameter ignoreCase=true, which allows parsing "west" ignoring case.
Given this code, how many key-value pairs does the dictionary contain after execution?
using System; using System.Collections.Generic; enum Level { Low = 1, Medium = 2, High = 3 } class Program { static void Main() { string[] inputs = { "Low", "Medium", "High", "low", "HIGH" }; var dict = new Dictionary<Level, int>(); foreach (var s in inputs) { if (Enum.TryParse<Level>(s, true, out var level)) { if (!dict.ContainsKey(level)) { dict[level] = 0; } dict[level]++; } } Console.WriteLine(dict.Count); } }
Consider that parsing is case-insensitive and dictionary keys are unique enum values.
All strings parse to one of three enum values: Low, Medium, High. Case differences do not create new keys. So dictionary has 3 keys.