Guide to the Language


Enum Access Levels and Scope


Download 2 Mb.
Pdf ko'rish
bet51/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   47   48   49   50   51   52   53   54   ...   78
Bog'liq
C sharp

 Enum Access Levels and Scope
The access levels for enumerations are the same as for classes. They 
are internal by default, but can also be declared as public. Although 
enumerations are usually defined at the top level, they may be contained 
within a class. In a class they have private access by default and can be set 
to any one of the access levels.
 Enum Methods
An enumeration constant can be cast to an int and the ToString method 
can be used to obtain its name.
static void Main()
{
State s = State.Run;
int i = (int)s; // 0
string t = s.ToString(); // Run
}
Several enumeration methods are available in the System.Enum class, 
such as GetNames() to obtain an array containing the names of the enum 
constants. Note that this method takes a type object (System.Type) as its 
argument, which is retrieved using the typeof operator.
enum Colors { Red, Green };
static void Main()
{
foreach (string s in System.Enum.GetNames(typeof(Colors)))
{
System.Console.Write(s); // "RedGreen"
}
}
Chapter 20 enum


121
© Mikael Olsson 2020 
M. Olsson, C# 8 Quick Syntax Reference
https://doi.org/10.1007/978-1-4842-5577-3_21
CHAPTER 21
Exception Handling
Exception handling allows programmers to deal with unexpected 
situations that may occur in programs. As an example, consider opening a 
file using the StreamReader class in the System.IO namespace. To see what 
kinds of exceptions this class may throw, you can hover the cursor over 
the class name in Visual Studio. For instance, you may see the System.IO 
exceptions FileNotFoundException and DirectoryNotFoundException. 
If any of those exceptions occurs, the program will terminate with an error 
message.
using System;
using System.IO;
class ErrorHandling
{
static void Main()
{
// Run-time error
StreamReader sr = new StreamReader("missing.txt");
}
}


122

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   47   48   49   50   51   52   53   54   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling