C # '(class) var' - what is this construction

I am trying to learn some C #, one of the code snippets I found:

(CheckBox)c

(where c was the result of foreach)

I understand that this makes the compiler know that c will behave like a flag, my question is: what is called this type of construct? I would like Google to better understand it.

Thank!

+4
source share
6 answers

. , , , c . MSDN. foreach - IEnumerable, , , , :

for (CheckBox c in xs) {
}

for (var c in xs.Cast<CheckBox>()) {
}

c CheckBox , . , , , ( , .NET 1.1 Java).

+4

c CheckBox. , c, CheckBox, , "IsChecked", "Name" ..

.

:

bool isItChecked = c.IsChecked; // this would not compile because object does not have a property "IsChecked"

, , , c CheckBox, :

var checkBoxC = (CheckBox)c; // The Cast
bool isItChecked = checkBoxC.IsChecked; // access the casted items properties.

- , " ", , .

PS: , # .

+2

"". :

( #)

+1

, casting. . MSDN. :

- , boxing and unboxing. MSDN

, object c checkbox. checkbox.

+1

. , , "c" . , c , InvalidCastException.

, # , , Generics

: , .

+1

It is called " Casting " or " UnBoxing "

static private void TestBoxingAndUnboxing()
{
 int i = 123;
 object o = i; // Implicit boxing
 i = 456; // Change the contents of i
 int j = (int)o; // Unboxing (may throw an exception if the types are incompatible)
}

//this function is about 2*Log(N) faster
static private void TestNoBoxingAndUnboxing()
{
 int i = 123;
 i = 456; // Change the contents of i
 int j = i; // Compatible types
}

Understand the difference between the two, although they do the same.

+1
source

Source: https://habr.com/ru/post/1534782/


All Articles