This code throwing out an error:
bool status1 = (bool)Cache["cache_req_head"];
bool status2 = (bool)Cache["cache_super"];
bool status3 = (bool)Cache["cache_head"];
This is how the cache variables were set:
if (checkreqhead == true)
{
Cache["cache_req_head"] = true;
}
else if (checksuper == true)
{
Cache["cache_super"] = true;
}
else if (checkhead == true)
{
Cache["cache_head"] = true;
}
Coming from PHP background, this is awkward. The error is:
Object reference not set to an instance of an object
I'm certain it is something really simple, but probably I can't spot it.
THANKS ALL FOR HELPING :)
"Object reference not set to an instance of an object" is c# lingo for "you did something stupid with a null value"
If the Cache is empty you need to check that first
bool status1 = (bool)Cache["cache_req_head"];
should be
bool status1 = false;
if (Cache["cache_req_head"] != null)
{
status1 = (bool)Cache["cache_req_head"];
}
This is an effect of the fact that value types (like bool, int, etc) in c# can not be null. There is a wrapper, Nullable<T> with the shorthand T? that you can use if you want to allow null values for the value types.
You can cast your value to a bool? since that allows for null.
bool? status1 = (bool?)Cache["cache_req_head"];
You can then check status1 == null or status1.HasValue, to get the actual bool value you need to pick it out with status1.Value. If you pick status1.Value while status1 == null you will get a runtime exception like the one you just got.
Actually, the best way to check for whether a value exists or not in Cache is by doing:
//string is used as an example; you should put the type you expect
string variable = Cache["KEY"] as string;
if(variable!=null)
{
// do something
}
The reason why doing if(Cache["KEY"]!=null) myVariable=Cache["Key"]; is unsafe, is because the object stored in Cache["Key"] may be removed from Cache before you get a chance to assign it to myVariable and you end up thinking that myVariable holds a non-null value.
You obviously only setting one of the cache entries at a time. So unless you run the "setter" code 3 times with only 1 variable set to true, then you always going to have nulls returned.
null does not cast into bool because its a value type. Try using bool?
Since Cache[] returns an object, which is null if not set, then you're getting an exception trying to cast null into a bool.
You'd have to check if that key exists first, or you'd have to set each key to "false" as a default.
Related
For some reason this if statement is invalid and it says: "Use of unassigned local variable 'I1'.
I can't figure out what is wrong with this if statement and it's bothering me.
I am using VisualStudio 2019, and I can't figure out how to fix it.
bool I1;
if (I1 == true)
{
}
The line 'Bool I1;' creates a variable, but doesn't assign it any value. Your if statement is asking "does this thing with no value equal something" and the compiler is politely letting you know that it's not bothered to do that. Presumably you'd want something like
bool I1 = GetValueOfI1Method();
if(I1) //if(I1) is functionally equivalent to if(I1 == true) but generally more readible
{
//do stuff
}
I'm guessing/hoping you have some code that could potentially assign a value to I1, if you want to use your if statement anyway what you can do is use a nullable boolean
bool? I1 = null; //use a nullable bool
//code which might assign a value to foo
...
//if statement to check if a value has been assigned and if it's true
if(I1.HasValue && I1.Value) //has anyone assigned a value to I1 and if so is that value true
{
}
Realistically you'd never bother to do the above with a bool, you'd just set it to false and run a method that might possibly set it to true (or the inverse)
I'm attempting to convert an object to a bool type and want to convert bool and Nullable<bool> types. I also want to make sure I make the appropriate casts where possible. So I have the following code:
if (value is bool)
{
boolValue = (bool) value;
}
else if (value is bool? && ((bool?)value).HasValue)
{
boolValue = ((bool?) value).Value;
}
else
{
throw new ArgumentException("Value must be a boolean type");
}
ReSharper 2016 informs me that value is bool? will always evaluate to false in this stack of if statements. Why is that? That would imply that Nullable<bool> doesn't inherit from object (impossible) or that value is bool will capture a bool?.
It's also possible that ReSharper 2016 has a bug; I see that the implementation of System.Windows.Controls.BooleanToVisibilityConverter.Convert is pretty much identical. I doubt that WPF core would have such a mistake in it, leading me to believe it's an issue with ReSharper.
When a value type is stored as object it is boxed. Boxing of Nullable<T> gets special treatment:
Objects based on nullable types are only boxed if the object is non-null. If HasValue is false, the object reference is assigned to null instead of boxing ... Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable that wraps the value type.
And, per the documentation for is:
An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.
So, using both of these you can deduce (see fiddle) that in the null case:
bool? x = null;
object obj = x; // assigns obj = null
obj is bool? // false, obj is null
obj is bool // false, obj is null
And in the non-null case:
bool? x = true;
object obj = x; // obj is boxed bool (true)
obj is bool? // true, obj unboxes to bool?
obj is bool // true, obj unboxes to bool
So ReSharper is correct: your first branch will evaluate as true if value is true or false (whether the object was assigned from a bool or bool? is not relevant or even known). The second branch will always be false in this case.
So I have a bool variable like this in model.
bool Foo;
I am receiving data from server and de-serialize it model object. So whatever fields are not there in server data gets initialized to defaults. And default(bool) is false.
But value false is also an acceptable value for my variable Foo. So is there some way to check if it gets value false from server or its default.
I also have same issue with other types like int, double etc. which doesn't defaults to null.
In your place, I'd use Nullable<bool> (bool?) to your purposes. Then you will be able to check value in this way:
bool? Foo;
if(Foo.HasValue)
{
// do something with Foo.Value
}
else
{
// Foo is uninitialized
}
On my system (Microsoft (R) Visual C# Compiler version 4.7.3190.0) the accepted answer isn't complete: compiler error. Just need to initialize to null variable declaration. so:
bool? Foo = null;
if (Foo.HasValue)
{
// do something with Foo.Value
}
else
{
// Foo is uninitialized
}
Error : cannot implicitly convert type 'bool?' to 'bool'. An explicit
conversion exists (are you missing a cast?)
Code :
Test obj = new Test();
obj.IsDisplay = chkDisplay.IsChecked;
but when I use this method to cast the property into a bool then there is no error.
Test obj = new Test();
obj.IsDisplay = (bool) chkDisplay.IsChecked;
I would like to know why I need to cast this bool to bool?
As the others stated bool? is not equal to bool. bool? can also be null, see Nullable<t> (msdn).
If you know what the null state wants to imply, you easily can use the ?? - null-coalescing operator (msdn) to convert your bool? to bool without any side effects (Exception).
Example:
//Let´s say "chkDisplay.IsChecked = null" has the same meaning as "chkDisplay.IsChecked = false" for you
//Let "check" be the value of "chkDisplay.IsChecked", unless "chkDisplay.IsChecked" is null, in which case "check = false"
bool check = chkDisplay.IsChecked ?? false;
You've declared IsChecked as a bool? (Nullable<bool>). A nullable boolean can be either true, false or null. Now ask yourself: If IsChecked was null, then what value should be assigned to IsDisplay (which can only take a true or false)? The answer is that there is no correct answer. An implicit cast here could only produce hidden trouble, which is why the designers decided to only allow an explicit conversion and not an implicit one.
I'm facing your question when I'm using the null check operator ?.:
if (!RolesList?.Any()) //Not accepted: cannot convert bool? to bool
So I'm using this instead
if (RolesList?.Any() != true)
//value is null or false
In your case you should set it like so:
obj.IsVisible = chkDisplayStuff.IsChecked ?? false;
bool? is not a bool. It is in reality a Nullable<bool>
http://msdn.microsoft.com/en-us/library/b3h38hb0(v=vs.110).aspx
If you need the bool value then you should either cast like you are doing or call the .Value property on the bool?. There is also a .HasValue property you can check to make sure that it is not null.
If IsChecked is null, this line will error.
obj.IsDisplay = (bool) chkDisplay.IsChecked;
bool is not equal to bool?.
bool can take two values, true and false.
bool? can take three, true, false, and null.
That is why they are different.
You can use below code
obj.IsDisplay = chkDisplay.IsChecked == true?true:false;
chkDisplay.IsChecked is of type bool?. Which means it can hold values true, false and null.
However, obj.IsDisplay is of type bool. Which means it can only hold true or false.
Hence you have to explicitly cast it to type bool. However, this will still throw an exception if, the value you are trying to cast to bool is null.
bool? nullableBool = null;
bool notNullableBool = (bool)nullableBool; //This will throw InvalidOperationException
Try this
if (asset.IsUp ?? false)
cast your nullable value to value type
[HttpPost]
public ActionResult Index(bool? checkOffAge)
{
if (checkOffAge != null) {
model.CheckOffAge =(bool)checkOffAge;
}
}
I want to check if a variable is initialized at run time, programmatically. To make the reasons for this less mysterious, please see the following incomplete code:
string s;
if (someCondition) s = someValue;
if (someOtherCondition) s = someOtherValue;
bool sIsUninitialized = /* assign value correctly */;
if (!sIsUninitialized) Console.WriteLine(s) else throw new Exception("Please initialize s.");
And complete the relevant bit.
One hacky solution is to initialize s with a default value:
string s = "zanzibar";
And then check if it changed:
bool sIsUninitialized = s == "zanzibar";
However, what if someValue or someOtherValue happen to be "zanzibar" as well? Then I have a bug. Any better way?
Code won't even compile if the compiler knows a variable hasn't been initialized.
string s;
if (condition) s = "test";
// compiler error here: use of unassigned local variable 's'
if (s == null) Console.Writeline("uninitialized");
In other cases you could use the default keyword if a variable may not have been initialized. For example, in the following case:
class X
{
private string s;
public void Y()
{
Console.WriteLine(s == default(string)); // this evaluates to true
}
}
The documentation states that default(T) will give null for reference types, and 0 for value types. So as pointed out in the comments, this is really just the same as checking for null.
This all obscures the fact that you should really initialize variables, to null or whatever, when they are first declared.
With C# 2.0, you have the Nullable operator that allows you to set an initial value of null for heretofore value types, allowing for such things as:
int? x = null;
if (x.HasValue)
{
Console.WriteLine("Value for x: " + num.Value);
}
Which yields:
"Value for x: Null".
Just assign it null by default, not a string value
Here's one way:
string s;
if (someCondition) { s = someValue; }
else if (someOtherCondition) { s = someOtherValue; }
else { throw new Exception("Please initialize s."); }
Console.WriteLine(s)
This might be preferable for checking if the string is null, because maybe someValue is a method that can sometimes return null. In other words, maybe null is a legitimate value to initialize the string to.
Personally I like this better than an isInitialized flag. Why introduce an extra flag variable unless you have to? I don't think it is more readable.
You can keep a separate flag that indicates that the string has been initialized:
string s = null;
bool init = false;
if (conditionOne) {
s = someValueOne;
init = true;
}
if (conditionTwo) {
s = someValueTwo;
init = true;
}
if (!init) {
...
}
This will take care of situations when s is assigned, including the cases when it is assigned null, empty string, or "zanzibar".
Another solution is to make a static string to denote "uninitialized" value, and use Object.ReferenceEquals instead of == to check if it has changed. However, the bool variable approach expresses your intent a lot more explicitly.
I would agree with Vytalyi that a default value of null should be used when possible, however, not all types (like int) are nullable. You could allocate the variable as a nullable type as explained by David W, but this could break a lot of code in a large codebase due to having to refine the nullable type to its primitive type before access.
This generic method extension should help for those who deal with large codebases where major design decisions were already made by a predecessor:
public static bool IsDefault<T>(this T value)
=> ((object) value == (object) default(T));
If you are staring from scratch, just take advantage of nullable types and initialize it as null; that C# feature was implemented for a reason.
I pick initialization values that can never be used, typical values include String.Empty, null, -1, and a 256 character random string generator .
In general, assign the default to be null or String.Empty. For situations where you cannot use those "empty" values, define a constant to represent your application-specific uninitialized value:
const string UninitializedString = "zanzibar";
Then reference that value whenever you want to initialize or test for initialization:
string foo = UnininitializedString;
if (foo == UninitiaizedString) {
// Do something
}
Remember that strings are immutable constants in C# so there is really only one instance of UninitializedString (which is why the comparison works).