Workings
"Switch statements"
These are my study notes relating to an exercise in Microsoft Learn
Complete a challenge activity using switch statement
Quick breakdown of the SKU reference:
string sku = "01-MN-L";
string[] product = sku.Split('-');
string type = "";
string color = "";
string size = "";
if (product[0] == "01")
{
type = "Sweat shirt";
} else if (product[0] == "02")
{
type = "T-Shirt";
} else if (product[0] == "03")
{
type = "Sweat pants";
}
else
{
type = "Other";
}
Due to zero indexing the elements in the product serial number are as follows:
- product[0] = “01” (type)
- product[1] = “MN” (color)
- product[2] = “L” (size)
To convert the “if, else if, else” statement to a “switch” statement refactor the code as follows:
switch (product[0])
{
case "01":
type = "Sweat shirt";
break;
case "02":
type = "T-Shirt";
break;
case "03":
type = "Sweat pants";
break;
default:
type = "other";
break;
}
Continue through the remaining code refactoring the “if, else if, else” statements to “switch” statements as appropriate :wink:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Solution (with original code commented out:
// SKU = Stock Keeping Unit.
// SKU value format: <product #>-<2-letter color code>-<size code>
string sku = "01-MN-L";
string[] product = sku.Split('-');
string type = "";
string color = "";
string size = "";
/*if (product[0] == "01")
{
type = "Sweat shirt";
} else if (product[0] == "02")
{
type = "T-Shirt";
} else if (product[0] == "03")
{
type = "Sweat pants";
}
else
{
type = "Other";
}
*/
switch (product[0])
{
case "01":
type = "Sweat shirt";
break;
case "02":
type = "T-Shirt";
break;
case "03":
type = "Sweat pants";
break;
default:
type = "other";
break;
}
/*
if (product[1] == "BL")
{
color = "Black";
} else if (product[1] == "MN")
{
color = "Maroon";
} else
{
color = "White";
}
*/
switch (product[1])
{
case "BL":
color = "Black";
break;
case "MN":
color = "Maroon";
break;
default:
color = "White";
break;
}
/*if (product[2] == "S")
{
size = "Small";
} else if (product[2] == "M")
{
size = "Medium";
} else if (product[2] == "L")
{
size = "Large";
} else
{
size = "One Size Fits All";
}
*/
switch (product[2])
{
case "S":
size = "Small";
break;
case "M":
size = "Medium";
break;
case "L":
size = "Large";
break;
default:
size = "One size fits all";
break;
}
Console.WriteLine($"Product: {size} {color} {type}");
W3C If,Else if,Else Statement
W3C Switch Statement