Answer the question
In order to leave comments, you need to log in
WITH#. Why do local variables defined in a method need to be set to an initial value, but class fields can be omitted?
WITH#. Why do local variables defined in a method need to be set to an initial value, but class fields can be omitted?
Answer the question
In order to leave comments, you need to log in
Because the class field is automatically initialized with a default value before the constructor is executed.
class Test
{
public int a = 10;
public int b; // автоматически будет 0
public int с; // тут сначала будет 0, потом в конструкторе станет 20
public Test()
{
c = 20;
}
}
And here and there you can not ask, you need to understand what you want to do.
using System;
public class Test<T>
{
// Перед вызовом конструктора выставится в default(int), то есть 0
private int i;
// Для ссылочного типа default(object) будет null
private object obj;
// default(T)
private T t;
public Test()
{
// Не инициализированная переменная
int foo;
// error CS0165: Use of unassigned local variable 'foo'
Console.WriteLine(foo.ToString());
foo = 0;
// У foo появилось значение, теперь переменной можно пользоваться
Console.WriteLine(foo.ToString());
int bar;
// error CS0165: Use of unassigned local variable 'bar'
Ref(ref bar);
// Для ref нужна инициализированная переменная
Ref(ref foo);
// Для out не нужна
Out(out foo);
Out(out bar);
}
private void Ref(ref int r)
{
r = 0;
}
private void Out(out int o)
{
o = 0;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question