Why does CodeRush warn me of an Unused Declaration in code?

让人想犯罪 __ 提交于 2020-01-06 15:12:49

问题


I have this code, which I use all over my applications to save data back to the database.

    public bool SaveDemo()
    {
        bool success = false;

        try
        {
            using (DataTable dt = DataAccess.ExecuteDataTable("[dbo].[udp_Customers_ups]",
                DataAccess.Parameter(CustomerIdColumn, CustomerId),
                DataAccess.Parameter(CodeColumn, Code),
                DataAccess.Parameter(CompanyColumn, Company),
                DataAccess.Parameter(IsDeletedColumn, IsDeleted),
                DataAccess.Parameter(LastUpdatedColumn, LastUpdated),
                DataAccess.Parameter(UpdatedByColumn, UpdatedBy)))

                success = true;
        }
        catch
        {
            success = false;
        }

        return success;
    } 

The code works as is, which by that I mean it saves the data back to the database. However CodeRush complains about the dt being an Unused Declaration. And since the Using is (I think) using the dt I would think that the warning is a false positive. So I am left wondering if CodeRush is wrong or if I am missing something?


回答1:


What CR is trying to say is that in:

using (DataTable dt =  DataAccess.ExecuteDataTable ... 

you are not using the declaration of dt; the variable remains untouched after.

The refactor button will transform this to

using ( DataAccess.ExecuteDataTable ... 

i.e. it will still be a using statement but you won't have a variable to refer to it.

While you're doing that, you can do some Inline Result transformations, yielding:

    try
    {
        using (DataAccess.ExecuteDataTable("[dbo].[udp_Customers_ups]",
            DataAccess.Parameter(CustomerIdColumn, CustomerId),
            DataAccess.Parameter(CodeColumn, Code),
            DataAccess.Parameter(CompanyColumn, Company),
            DataAccess.Parameter(IsDeletedColumn, IsDeleted),
            DataAccess.Parameter(LastUpdatedColumn, LastUpdated),
            DataAccess.Parameter(UpdatedByColumn, UpdatedBy)))
            return true;
    }
    catch
    {
        return false;
    }

I'll let others question whether wrapping calls like this in a catch block is a good idea...



来源:https://stackoverflow.com/questions/29448120/why-does-coderush-warn-me-of-an-unused-declaration-in-code

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