I have been developing for windows mobile and android for sometime. And I’m confused about these two concepts.
Let’s say I want to make decision based on some the user’s device Screen Size. So I’ll expect so predefined values. I could use a switch statement for handling my logic.
But I’m not sure whether I should use Enum of a Static Class for this purpose. Which one is a better approach.
I can do my logic in these two different ways. Which one is the correct approach? I’m confused. And is it possible for me to use String values also? Because currently I’m sticking with classes, I need to update to use all enums. So How about changing my Class to String Enum? Any way. Thanks.
Using Enum
//My predefined values
public enum ScreenSizeEnum
{
Small, Medium, Large, XLarge,
}
//Handling Logic
private void SetScreenSize(ScreenSizeEnum Screen)
{
switch (Screen)
{
case ScreenSizeEnum.Large:
//Do Logic
break;
case ScreenSizeEnum.Small:
//Do Logic
break;
}
}
Using Class
//My predefined values
public class ScreenSizeClass
{
public const int Small = 0;
public const int Medium = 1;
public const int Large = 2;
public const int XLarge = 3;
}
//Handling Logic
private void SetScreenSize(int Screen)
{
switch (Screen)
{
case ScreenSizeClass.Large:
//Do Logic
break;
case ScreenSizeClass.Small:
//Do Logic
break;
}
}
From Enumeration Types (C# Programming Guide):
So if you pass
enum, it is strongly typed, so you automatically get control over what you can pass into a method.When using
constorstaticfields you definitely need to check whether the passedintvalue is taken from the expected diapason.Based on comments:
If it’s necessary to check, whether some
intis defined inenum, one can do something like this:Or an extension method:
which could be used
As for the
string(based on OP’s edited question):From enum (C# Reference):
So you cannot have an enum of strings. But you can use names from enums, as
ToStringmethod returns the name, not the value of the enum.So you can have another extension method on strings:
So that