Студопедия — Task 1 – Declaring Simple Implicitly Typed Local Variables and Arrays
Студопедия Главная Случайная страница Обратная связь

Разделы: Автомобили Астрономия Биология География Дом и сад Другие языки Другое Информатика История Культура Литература Логика Математика Медицина Металлургия Механика Образование Охрана труда Педагогика Политика Право Психология Религия Риторика Социология Спорт Строительство Технология Туризм Физика Философия Финансы Химия Черчение Экология Экономика Электроника

Task 1 – Declaring Simple Implicitly Typed Local Variables and Arrays






This task starts with simple examples to enable understanding of var.

 

1. Add a new method above Main called VarTest thatcreates a few simple objects and one slightly more complex:

static void VarTest()

{

int i = 43;

 

string s = "...This is only a test...";

 

int[] numbers = new int[] { 4, 9, 16};

 

SortedDictionary<string, List<DateTime>> complex =

new SortedDictionary<string, List<DateTime>>();

}

 

static void Main(string[] args)

 

2. Press Ctrl+Shift+B to build the solution to ensure everything compiles (the two warnings that appear are expected).

3. Now make the identified changes in VarTest (changing the types to var as well as removing the type, int, from the initialization of the array):

static void VarTest()

{

var i = 43;

 

var s = "...This is only a test...";

 

var numbers = new [] { 4, 9, 16 };

 

var complex = new SortedDictionary<string, List<DateTime>>();

}

 

4. Press Ctrl+Shift+B to build the solution to ensure everything compiles.

5. Now move the mouse over each var and notice that the type has been inferred for each. Two examples are shown below.

View the quick info for the array of numbers (move the mouse over var next to numbers) to notice the type of the list created was inferred by the type of data provided in the list.

 

Task 2 – Create an Implicitly Typed Array (and understand the restrictions of Implicit Typing)

There are some restrictions on the use of implicitly typed local variables. In particular, because the type of the variable is inferred from its initialization, an implicitly typed declaration must include an initialization. This task works through the errors that could arise when trying to build an array of integers.

 

1. In the VarTest method, replace the body with the following code:

static void VarTest()

{

var x; // Error: what type is it?

x = new int[] { 1, 2, 3 };

}

 

static void Main(string[] args)

 

2. Press Ctrl+Shift+B to build the solution

3. Click the Error List tab to view the compiler error output.

Because the type of the variable is inferred from its initializer, an implicitly typed declaration must include an initializer.

 

4. Replace the variable declaration in the VarTest method with the following code:

static void VarTest()

{

var x = {1, 2, 3}; // Error: array initalization expression not permitted

}

 

5. Press Ctrl+Shift+B to build the solution and view the resulting compiler errors.

An implicit array initialization expression must specify that an array is being created and include new[]. Also important to note when using implicitly typed local variables, the initializer cannot be an object or collection initializer by itself. It can be a new expression that includes an object or collection initializer.

 

6. Fix the errors by replacing the line with:

static void VarTest()

{

var x = new[] {1, 2, 3};

}

 

7. Press Ctrl+Shift+B to build the solution. This time the solution builds.

Now the code compiles and the type has been inferred. Move the mouse over var and the Quick Info shows the inferred type: Int32[].

8. Delete the VarTest method to reduce clutter.

 

Implicitly typed variables shouldn’t be confused with scripting languages where a variable can hold values of different types over its lifetime in a program (the equivalent of that in C# is object). Instead, this feature affects only the declaration of variables at compile time; the compiler infers the type of the variable from the type of expression used to initialize it. From then on throughout the program, it is as if the variable was declared with that type; assigning a value of a different type into that variable will result in a compile time error.

 







Дата добавления: 2015-09-07; просмотров: 429. Нарушение авторских прав; Мы поможем в написании вашей работы!



Кардиналистский и ординалистский подходы Кардиналистский (количественный подход) к анализу полезности основан на представлении о возможности измерения различных благ в условных единицах полезности...

Обзор компонентов Multisim Компоненты – это основа любой схемы, это все элементы, из которых она состоит. Multisim оперирует с двумя категориями...

Композиция из абстрактных геометрических фигур Данная композиция состоит из линий, штриховки, абстрактных геометрических форм...

Важнейшие способы обработки и анализа рядов динамики Не во всех случаях эмпирические данные рядов динамики позволяют определить тенденцию изменения явления во времени...

Расчет концентрации титрованных растворов с помощью поправочного коэффициента При выполнении серийных анализов ГОСТ или ведомственная инструкция обычно предусматривают применение раствора заданной концентрации или заданного титра...

Психолого-педагогическая характеристика студенческой группы   Характеристика группы составляется по 407 группе очного отделения зооинженерного факультета, бакалавриата по направлению «Биология» РГАУ-МСХА имени К...

Общая и профессиональная культура педагога: сущность, специфика, взаимосвязь Педагогическая культура- часть общечеловеческих культуры, в которой запечатлил духовные и материальные ценности образования и воспитания, осуществляя образовательно-воспитательный процесс...

Метод архитекторов Этот метод является наиболее часто используемым и может применяться в трех модификациях: способ с двумя точками схода, способ с одной точкой схода, способ вертикальной плоскости и опущенного плана...

Примеры задач для самостоятельного решения. 1.Спрос и предложение на обеды в студенческой столовой описываются уравнениями: QD = 2400 – 100P; QS = 1000 + 250P   1.Спрос и предложение на обеды в студенческой столовой описываются уравнениями: QD = 2400 – 100P; QS = 1000 + 250P...

Дизартрии у детей Выделение клинических форм дизартрии у детей является в большой степени условным, так как у них крайне редко бывают локальные поражения мозга, с которыми связаны четко определенные синдромы двигательных нарушений...

Studopedia.info - Студопедия - 2014-2024 год . (0.011 сек.) русская версия | украинская версия