How to specify Ensures for out parameter?

半腔热情 提交于 2019-12-10 18:28:08

问题


I have a method with an out parameter and I want to specify using Contract.Ensures() that when the method returns, the parameter will not be null.

Basically, this:

void M(out object o)
{
    Contract.Ensures(o != null);

    o = new object();
}

This does not compile, because it looks like the parameter will be read before it's assigned:

error CS0269: Use of unassigned out parameter 'o'

I thought I could fix this by switching the lines around, but that does not work either:

warning CC1005: CodeContracts: Malformed contract. Found Ensures after assignment in method 'M(System.Object@)'.

Is there some way to do this?

I don't want to switch the method to ref. I can't return the value instead of using out, because the actual method where I encountered this already has a return value: bool TryGetValue(TKey1 key1, TKey2 key2, out TValue value).


回答1:


The Contract.ValueAtReturn method is available specifically to avoid the C# compiler's error here.

Contract.Ensures(Contract.ValueAtReturn(out o) != null);


来源:https://stackoverflow.com/questions/38153285/how-to-specify-ensures-for-out-parameter

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