What is main use of Enumeration?

后端 未结 10 1793
时光取名叫无心
时光取名叫无心 2020-12-08 07:35

What is main use of Enumeration in c#?

Edited:- suppose I want to compare the string variable with the any enumeration item then how i can do this

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 08:22

    There are two meanings of enumeration in C#.

    An enumeration (noun) is a set of named values. Example:

    public enum Result {
      True,
      False,
      FileNotFound
    }
    

    Enumeration (noun form of the verb enumerate) is when you step through the items in a collection.

    The IEnumerable interface is used by classes that provide the ability to be enumerated. An array is a simple example of such a class. Another example is how LINQ uses it to return results as enumerable collections.

    Edit:

    If you want to compare a string to an enum value, you either have to parse the string to the enum type:

    if ((Result)Enum.Parse(typeof(Result), theString) == Result.True) ...
    

    or convert the enum value to a string:

    if (theString == Result.True.ToString()) ...
    

    (Be careful how you compare the values, depending on whether you want a case sensetive match or not.)

    If you want to enumerate a collection and look for a string, you can use the foreach command:

    foreach (string s in theCollection) {
      if (s == theString) {
        // found
      }
    }
    

提交回复
热议问题