简体   繁体   中英

C# Static class with Enum

I have a tricky question that has been befuddling me for a while. I have the following code declaration...

namespace ESEGURCI.WEB.BusinessLogicLayer.Commons
{
    public static class ParameterUtilities
    {
        public enum ParameterEnum
        {
            MAX_LOGIN_ATTEMPTS,
            AUDIT_MODIFICATIONS
        }
    }
}

and I call the code like so " ParameterUtilities.ParameterEnum.MAX_LOGIN_ATTEMPTS " Problem is once every full moon I get the error "object reference not set to an instance of an object" on this line... It's like the code only works 99.9% of the time...

The only thing that occurs to me is that since the enum is a value type that there can be a chance that the enum is null when the static class is called... But I can't find any documentation on this behavior...

Can someone enlighten me why this happens? I know I should probably remove the enum out of the static class, and declare the enum as standalone but I'd like to know why this is happening first...

Thanks, S

Update

Ok, to everyone who asked for more code, the following is the full function where the error occurs...

    public static int GetPageSize(int companyId)
    {
        int pageSize = 0;

        // error happens bellow this line

        ESEGURCI.WEB.BusinessLogicLayer.Entities.Parameter parameter = ESEGURCI.WEB.BusinessLogicLayer.Entities.Parameter.GetParameter(ParameterUtilities.ParameterEnum.AUDIT_MODIFICATIONS.ToString(), companyId);

        // error happens above this line

        int.TryParse(parameter.Value, out pageSize);

        return pageSize;
    }

ParameterUtilities.ParameterEnum.MAX_LOGIN_ATTEMPTS won't ever throw a null reference exception, no matter what the Moon looks like. The error is probably triggered by an other instruction on the same line (assignment to a variable?).

An enum can't be null .

Split up the line as in the listing below and see which statement throws the exception. I bet it happens somewhere in Parameter.GetParameter() :

using ESEGURCI.WEB.BusinessLogicLayer.Entities;

// ...

var auditModifications = 
    ParameterUtilities.ParameterEnum.AUDIT_MODIFICATIONS.ToString();
var parameter = Parameter.GetParameter(auditModifications, companyId);

Enum (and any other type) cannot have null value, because it isn't a value it is a type.

The exception is thrown by something else.

As already stated your enum will not be where the error is coming from. Based on your update, I would say the NRE is most likely coming from your GetParameter method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM