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.
Related
sistematically, but only on one PC, while executing this code:
using Microsoft.Ink;
...
Tablets allTablets = new Tablets();
int numTablet = allTablets.Count;
I get this exception.
System.ArgumentException: Valore non compreso nell'intervallo previsto. {In English --> Value not in the right range}
in Microsoft.Ink.InkTabletsClass.get_Count()
in Microsoft.Ink.Tablets.get_Count()
How could a COUNT throw this kind of exception?
Does it means that the Count method return a value that is not int?
Thanks.
How could a COUNT throw this kind of exception?
Because of some logic that is implemented in the getter of the Count property of the Tablets class. It is in the getter that the exception is thrown.
Does it means that the Count method return a value that is not int?
No. An int property can only return an int value or throw an exception. It can never return a value of any other type. The compiler enforces this.
I tried your code, and it works for me. That being said, I have encountered similar exceptions so many times before that I now make it a habit to check for null objects first. So, I would use:
Tablets allTablets = new Tablets();
int numTablet = 0;
if (allTablets != null)
numTablet = allTablets.Count;
To answer your question, for some reason new Tablets() returns null instead of an empty ICollection.
So i have this old code that uses Firebird, i took the code from there since it worked perfectly, but here it doesnt. and throws me a InvalidCastException.
So wat am i trying
animal.FeedScheduleType = (BcFeedScheduleType)drAnimal["feedschedule_type"];
So i try to pull something out my datatable and place it in animal.FeedScheduleType. Now my cast points a a public enum
public enum BcFeedScheduleType
{
Default = 0,
FromList = 1,
Group = 2
}
and animal.FeedScheduleType is
private BcFeedScheduleType _feedScheduleType;
public BcFeedScheduleType FeedScheduleType
{
get { return _feedScheduleType; }
set { _feedScheduleType = value; }
}
But whenever it hits this it throws me the InvalidCastException error and i dont know why, i searched here and google but was unable to find anything about casts like this.
Edit: the Type inside the database is a integer
Try this:
animal.FeedScheduleType = (BcFeedScheduleType)Convert.ToInt32(drAnimal["feedschedule_type"]);
Here is a fiddle.
Have you tried casting to an int first?
animal.FeedScheduleType = (BcFeedScheduleType)(int)drAnimal["feedschedule_type"];
My guess is that your drAnimal is returning a string and not an int. If this is the case, then
animal.FeedScheduleType = (BcFeedScheduleType)Int.Parse(drAnimal["feedschedule_type"]);
If you are not sure what type drAnimal is, you can do something like:
var feedschedule_type = drAnimal["feedschedule_type"];
Console.WriteLine("feedschedule_type is {0}", typeof(feedschedule_type));
Basically, you need to get it into an int and then use the standard cast as you've done in your question.
Finally, make sure the feed schedule type has a valid value. I.e., make sure its value is either 0, 1 or 2.
I actually just ran into this recently when using SqlParameter.
My guess is that drAnimal["feedschedule_type"] is being stored as a SqlDbType.Int or object. In order to cast my parameter, I had to do something similar to the following:
(int)(SqlDbType.Int)(drAnimal["feedschedule_type"]);
You may have to use a similar chain to get the actual int value and coerce it into your Enum.
Is there a way to know if an out parameter was set already or not. This is the pseudocode for what I am looking for:
public virtual string blabla(long num, out bool bval)
{
if (!bval.HasValue)
{
//Do some default logic
bval = defaultValue;
}
return blabla2(num, bval);
}
You can't - you can't read the variable until it's been definitely assigned within your method. You should think of it as being like a local variable, declared but not assigned any value at the start of the method - but which you must assign a value to before you return. (It's okay not to have assigned a value to it if an exception is thrown.)
If you want a parameter which carries information as input to the method as well as propagating information out, you should use ref instead of out.
See my article on parameter passing for more information.
In addition to Jon's excellent answer, if you want the parameter to still be out, but need to see if it has been assigned a value at some place inside the method, you could use a local nullable type like follows:
public virtual string blabla(long num, out bool bval)
{
bool? bvalLocal;
... //I'm assuming there is some code here that may or
//may not assign bvalLocal?
// This whole if block may not be needed if the default
// value is the default for the type (i.e. false) as
// GetValueOrDefualt() will take care of that (see
// second to last line).
if (!bvalLocal.HasValue)
{
//Do some default logic
bvalLocal = defaultValue;
}
bval = bvalLocal.GetValueOrDefault();
return blabla2(num, bval);
}
Hello
I'm having an error with this code:
"The out parameter 'o_BlockingSquaresArr' must be assigned to before control leaves the current method"
Now this error paints each return statement of each method apart from the last one with red..
I don't understand what is the problem regarding my specific code
Please help me,
Thanks in Advance
internal bool isLegalMove(Square i_Move, out List<Square> o_BlockingSquaresArr)
{
bool result;
if (m_GameBoard[i_Move.RowIndex, (int)i_Move.ColIndex].Coin != null)
{
result = false;
m_MessageBuffer = "You have enterd a square which is already
occupied, please try again...";
m_ErrorFlag=true;
}
else
{
result = checkIfThereIsAtLeastOneSeqInOneDirection(i_Move,out o_BlockingSquaresArr);
}
return result;
}
internal bool checkIfThereIsAtLeastOneSeqInOneDirection(Square i_Move, out List<Square> o_BlockingSquaresArr)
{
const int k_EightDirections = 8;
bool isSequenceFound, finalRes = false;
for (int i = 1; i <= k_EightDirections; i++)
{
isSequenceFound = checkOpponentSequenceInDirection(i_Move, (eDirections)i, out o_BlockingSquaresArr);
if (isSequenceFound)
{
finalRes = true;
}
}
return finalRes;
}
internal bool checkOpponentSequenceInDirection(Square i_Move, eDirections i_Direction, out List<Square> o_BlockingSquaresArr)
{
//I've shortened this code only relevant things
Square o_AdjacentSquare = new Square();
adjacentCoin = doSwitchAndRetrieveAdjacentCoin(i_Move, i_Direction, out o_AdjacentSquare);
// ...
if (isThereAnOpponentSequence)
{
o_BlockingSquaresArr.Add(o_AdjacentSquare);
}
return isThereAnOpponentSequence;
}
As the compiler error says, an out parameter has to be definitely assigned before any non-exceptional return of a method. I can't see any assignment to o_BlockingSquaresArr anywhere. Why are you even declaring it as an out parameter to start with?
An out parameter must be assigned a value before the method returns. In your isLegalMove method, o_BlockingSquaresArr is only assigned in the else block, so the compiler detects there are some cases where it is not initialized. You must make sure that all code paths in the method assign a value to o_BlockingSquaresArr before returning
You need to assign something to the out parameter in every execution path. In your case, you forget that in one case. Simply assign a default value of the beginning of the method so you don't run into it.
I can't tell you where as you didn't include the method name it is happening in.
In the IsLegalMove function, you need to assign a value to the o_BlockingSquaresArr variable
You need to assign something to out parameters in every (normally terminating) codepath. And you don't do that.
For example in some functions you only assign to the parameter inside the for-loop. And if the loop has 0 iterations this will never happen.
Okay, for whatever reason I can't seem to figure this little problem out.
I have the following enum:
public enum EFeedType
{
TypeOne = 1,
TypeTwo = 2
}
Now, I am going to be getting the numeric value from a database. Well, I need to cast the int value from the DB to the enum type:
EDIT:
The database type is integer, so I do not need to cast from string.
END EDIT
EFeedType feedType = (EFeedType) feedId;
However, when I do this, and pass in value of 2 I get the following error:
Instance validation error: '2' is not a valid value for [Namespace Goes Here].EFeedType.
Any thoughts on what I might be doing wrong or missing?
EDIT
Here is the code I am using:
//GetFeed will return an int value which is pulled from the database
int feedId = new FeedEngine().GetFeed("FeedName");
//Convert the ID to the Enum
EFeedType feedType = (EFeedType) feedId;
//Set the User Control FeedType Enum to the enum
FeedControl.FeedType = feedType;
//Show the user control
FeedControl.Visible = true;
EDIT - More Info
Okay, after seeing JSkeet's response, I see that If my feedId = 1 then it will set the enum value to TypeTwo instead of TypeOne like it should. Maybe I need a Default = 0 value in my enum for this to work? But there has to be a better way, because what if my values are not in sequence.
Your error won't be coming from the line you showed it on. I strongly suspect it's coming from this line:
FeedControl.FeedType = feedType;
My guess is that that property is doing some validation - and that it doesn't know about the relevant value.
EDIT: Note that if you do want to find out if a value is valid, use Enum.IsDefined. Enum.Parse will not throw an exception for an incorrect numeric value, so long as it's in the right range.
Have you really posted the exact code of the enum? Because if it doesn't explicitly specify the "= 1" and "= 2" it will autoincrement from 0, and that will be your problem.
If you could demonstrate all of this with a short but complete program it would really help. There's no need to go to the database, and no need to do anything with a user control.
I just tried the following and it worked perfectly. You might want to break your code out into a little test project to see what's going on.
// enum definition
public enum EFeedType {
TypeOne = 1,
TypeTwo = 2,
}
// usage
private void TestEnum() {
Int32 feedId = 2;
EFeedType stuff = (EFeedType)Enum.Parse(typeof(EFeedType), feedId.ToString());
Response.Write(stuff.ToString());
}