S
S
splunk2016-02-18 11:31:40
C++ / C#
splunk, 2016-02-18 11:31:40

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

2 answer(s)
A
Alexey Pavlov, 2016-02-18
@splunk

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;
    }
}

D
Daniil Basmanov, 2016-02-18
@BasmanovDaniil

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;
    }
}

Read more on MSDN here and here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question