Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лаба №1 / books / csharp_ebook.pdf
Скачиваний:
48
Добавлен:
03.03.2016
Размер:
3.69 Mб
Скачать

Programmers Heaven: C# School

}

}

When we try to compile the above program, the compiler says:

Structs cannot contain explicit parameterless constructors

Here, the compiler says that it is illegal to define parameterless (no-argument) constructors in a struct.

Author's Note: struct is not a new concept. In C++, the struct is another way of defining a class (why?). Even though most of the time C++ developers use struct for lightweight objects holding just data, the C++ compiler does not impose this. C# structs are more restricted than classes because they are value types and can not take part in inheritance. Java does not provide struct at all.

structs as Value Types

We will now demonstrate the use of struct as a value-type through a simple program which passes a struct to some method that modifies it. We will use the Point struct that we defined earlier. The Test class containing the Main() method is:

class Test

 

{

 

static void Main()

 

{

 

Point pt = new Point(19, 12);

 

Console.WriteLine("Before calling ChangeIt(pt): pt

= {0}", pt);

ChangeIt(pt);

 

Console.WriteLine("After calling ChangeIt(pt): pt

= {0}", pt);

}

 

static void ChangeIt(Point point)

 

{

 

point.x = 6; point.y = 11;

Console.WriteLine("In the method ChangeIt(pt): point = {0}", point);

}

}

We initialized the Point (pt) with (19, 12) and called the method ChangeIt(), which modifies the location of the Point. We then printed the Point before, after and inside the ChangeIt() method. The output of the program is:

Before calling ChangeIt(pt): pt = (19, 12)

In the method ChangeIt(pt): point = (6, 11)

104

Programmers Heaven: C# School

After calling ChangeIt(pt): pt = (19, 12)

Press any key to continue

We can clearly see from the output that the value of Point did get changed inside the method (ChangeIt()), but this change did not reflect back on to the original struct, which printed it un-changed in the Main() method after the ChangeIt() method. This supports the fact that structs are treated as value types by C#.

Enumeration

Enumeration is a very good concept originally found in C++, but not in Java. C# supports enumerations using the enum keyword. Enumerations, like classes and structures, also allow us to define new types. Enumeration types contain a list of named constants. The list is called an enumerator list here while its contents are called enumerator identifiers. Enumerations are of integral types like int, short, byte,… (except the char type).

The Need for Enumeration

Before we go into the details of how to define and use enumerations, let us first consider why we need enumerations in the first place. Suppose we are developing a Windows Explorer type of program that allows the users to do different tasks with the underlying file system. In View Properties, we allow the user to see the sorted list of files/folders on the basis of name, type, size, or modification date. Let us write a function that takes a string whose value represents one of these four criteria.

public void Sort(string criteria)

{

switch(criteria)

{

case "by name":

// code to sort by name break;

case "by type":

// code to sort by type break;

case "by size":

// code to sort by size break;

case "by date":

// code to sort by modification date break;

default:

throw new Exception("Invalid criteria for sorting passed...");

}

}

105

Programmers Heaven: C# School

If the user selects the option to sort files/folders by name, we pass this function a string "by name" like this:

Explorer explorer = new Explorer();

// some code goes here

explorer.Sort("by name");

Here Explorer is the name of the class containing the Sort() method. As we pass the string value "by name" to the Sort() method, it compares it inside the switch…case block and will take appropriate action (sort items by name). But, if someone writes:

explorer.Sort("by extention");

or

explorer.Sort("irrelevant text");

The program will still get compiled but it will throw an exception at runtime, which if not caught properly, might crash the program (We will see more about exceptions in the coming lessons. Right now, just consider that the program will not execute properly and might crash if some irrelevant value is passed as a parameter to the Sort() method). There should be some method to check the value at compile-time in order to avoid a run-time collapse. Enumeration provides the solution for this type of a problem.

Using Enumeration (enum)

Enumerations are defined in C# using the enum keyword. The enumerator identifiers (named constants) are separated using a comma ','.

enum SortCriteria

{

ByName,

ByType,

BySize,

ByDate

}

Here, we have defined an enumeration named SortCriteria, which contains four constants: ByName, ByType, BySize and ByDate. Now, we can modify our Sort() method to accept a SortCriteria type enumeration only.

public void Sort(SortCriteria criteria)

{

switch(criteria)

106

Programmers Heaven: C# School

{

case SortCriteria.ByName: // code to sort by name

Console.WriteLine("Files/Folders sorted by name"); break;

case SortCriteria.ByType: // code to sort by type

Console.WriteLine("Files/Folders sorted by type"); break;

case SortCriteria.BySize: // code to sort by size

Console.WriteLine("Files/Folders sorted by size"); break;

case SortCriteria.ByDate:

// code to sort by modification date Console.WriteLine("Files/Folders sorted by modification date"); break;

}

}

Note that we did not have a default clause in the switch…case, because now it is impossible to pass un-allowed criteria either by mistake or intentionally as the compiler will check the criteria at compile time. Now, in order to call the Sort() method, we need to pass an instance of an enumeration of type SortCriteria, which can only take input from of the allowed four criterion, hence providing a compile time check for illegal criteria. We now call the Sort() method as:

Explorer explorer = new Explorer();

explorer.Sort(SortCriteria.BySize);

Alternatively, we can create an instance of SortCriteria and then pass it as an argument to Sort() as:

Explorer explorer = new Explorer();

SortCriteria criteria = SortCriteria.BySize;

explorer.Sort(criteria);

When we compile and run the above program, we see the following output:

Files/Folders sorted by size

Press any key to continue

107

Соседние файлы в папке books