Книга: Fedora™ Unleashed, 2008 edition

Creating Your Own Variables

Creating Your Own Variables

As you saw in the parameter list for Main() and the arg variable in your foreach loop, C# insists that each variable has a distinct data type. You can choose from quite a variety: Boolean for true/false values; string for text; int for numbers, float for floating-point numbers; and so on. If you want to be very specific, you can use int32 for a 32-bit integer (covering from -2147483648 to 2147483648) or int64 for a 64-bit integer (covering even larger numbers). But on the whole you can just use int and leave C# to work it out itself.

So now you can modify your program to accept two parameters, add them together as numbers, then print the result. This gives you a chance to see variable definitions, conversion, and mathematics, all in one. Edit the Main() method to look like this:

public static void Main (string[] args) {
 int num1 = Convert.ToInt32(args[0]);
 int num2 = Convert.ToInt32(args[1]);
 Console.WriteLine("Sum of two parameters is: " + (num1 + num2)");
}

As you can see, each variable needs to be declared with a type (int) and a name (num1 and num2), so that C# knows how to handle them. Your args array contains strings, so you need to explicitly convert the strings to integers with the Convert.ToInt32() method. Finally, the actual addition of the two strings is done at the end of the method, while they are being printed out. Note how C# is clever enough to have integer + integer be added together (in the case of num + num2), whereas string + integer attaches the integer to the end of the string (in the case of "Sum of two parameters is:" + the result of num1 + num2). This isn't by accident: C# tries to convert data types cleverly, and warns you only if it can't convert a data type without losing some data. For example, if you try to treat a 64-bit integer as a 32-bit integer, it warns you because you might be throwing a lot of data away.

Оглавление книги


Генерация: 0.036. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз