Avoid “Use of unassigned local variable” error

…衆ロ難τιáo~ 提交于 2019-12-01 06:29:30

Compiler is not smart enough to determine if the assignment would be made and hence the error.

You can't do anything about it, You have to assign it some default value, probably 0,-1, default(int) or int.MinValue

You should initialize the variables. The compiler will never trust you ;)

The other answers are correct. The easiest way to solve this problem is to initialize the locals.

I assume that you understand why the error is being produced: the compiler has no ability to know that the method called actually runs the lambda, and therefore no knowledge that the locals are initialized.

The only way to trick the compiler into not checking whether a variable is assigned is to make the variable non-local:

public void Test() {
    int[] id = new int[1];
    SomeObject[] someObject = new SomeObject[1];

    WithResource((resource) => {
        id[0] = 1;
        someObject[0] = SomeClass.SomeStaticMethod(resource);
    });

    Assert.IsNotNull(someObject[0]);
    Assert.AreEqual(id[0], someObject.Id);
}

Now you might say, well here I've clearly assigned id. Yes, but notice that the compiler does not complain that you've used id[0] before initializing it! The compiler knows that array element variables are initialized to zero.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!