Is it possible somethings like this:
var userAggregazione;
if (userAggregazione = YouTube.Actions.IsAccessTokenValid() != null)
{
}
IsAccessTokenValid() returns a userAggregazione instance or null. So, inside the if, I'd like to setup var userAggregazione, and check if it is null or not.
Is it possible?
not sure if I understand but let me attempt:
var userAggregazione = YouTube.Actions.IsAccessTokenValid();
if (userAggregazione == null)
{
// userAggregazione is null - do something
}
else
{
// it is not null - do something
}
It will work if there's an extra parentheses around the assignment, so that it will get evaluated before the != comparison.
MyClass userAggregazione;
if ((userAggregazione = YouTube.Actions.IsAccessTokenValid()) != null)
{}
edit2:
I assume the example is simplified, because normally you should do like this for clarity:
//my style preference is also to not use 'var' anyway
//when getting value from a function
//because it's not clear what the type is.
MyClass userAggregazione = YouTube.Actions.IsAccessTokenValid();
if (userAggregazione != null)
{}
Yes it is, you need to add some braces:
if ((userAggregazione = YouTube.Actions.IsAccessTokenValid()) != null)
Just ensure that IsAccessTokeValid does not throw any exceptions
Related
I have a method with the return type Fruit, that does the following:
Search for the right apple, if it matches return it; else
Search for the right banana, if it matches return it; else
Search for the right orange, if it matches return it; else
return null
Fruit is an interface that has the following:
bool Rotten { get; set; }
The problem is that when I try to use it:
store.GeTAFruit("magic apple").Rotten;
If it does not find the fruit it will return null, and that will give a NullReferenceException.
Of course I can surround it with a try catch but that means that every time I use this function I will have to surround it with try catch, that doesn't seem like a good idea at all.
I'm looking either for a solution to this problem, or rather what would be the best approach for this.
If GetAFruit can return null, then (and here's the technical bit): check for null:
var fruit = store.GetAFruit(...);
if(fruit != null) {
//... Do stuff
}
Simply check that store.GeTAFruit("magic apple") is not null:
if (store.GeTAFruit("magic apple") != null) {
}
There are two approaches if you do not want to use exception handling. But the essence of them is the same. You must evaluate the lookup result to test it for null before using it.
The first option is to assign the result of your lookup to a variable and then test if before you use it.
Fruit fruit = store.GeTAFruit("magic apple");
if(fruit != null)
{
//safely use your Rotten property
bool lFlag = fruit.Rotten;
}
An alternative is to test it like so ...
if(store.GeTAFruit("magic apple") != null)
{
store.GetTAFruit("magic apple").Rotten;
}
The benefits of the first approach is that you only perform the lookup once.
this may help
if (store.GeTAFruit("magic apple")!=null) {
store.GeTAFruit("magic apple").Rotten;
}
edit to make it a tiny bit more efficient:
var fruit = store.GeTAFruit("magic apple");
if (fruit!=null)) {
fruit.Rotten;
}
Define a NullFruit : IFruit. Return a instance of it if nothing is found.
what i am trying to do is check whether an item in a list box is selected.
The method is being run on a separate thread so i would need to use a method invoker i believe.
string list = "";
lbxList.Invoke(new MethodInvoker(delegate { list = lbxList.SelectedItem.ToString(); }));
if (list != null)
{
//do something
}
this code will blow up if the selected item is null because the string list wont hold it, so i would need a way to combine the top 2 lines into an if statement checking for null.
Thanks
This should do:
string list = "";
lbxList.Invoke(new MethodInvoker(delegate
{
if (lbxList.SelectedItem != null)
list = lbxList.SelectedItem.ToString();
}));
//do something
Just place the if-statement inside the anonymous method.
Note that .ToString is highly unlikely to ever return null for anything, the documentation of object.ToString states that overriding types should implement the method to return a meaningful value. Since we already know that .SelectedItem is not null, checking for null is not really necessary. You can leave it in if you really want, but if you're afraid that .ToString should return null, I would instead change the code to this:
string list = "";
lbxList.Invoke(new MethodInvoker(delegate
{
if (lbxList.SelectedItem != null)
list = lbxList.SelectedItem.ToString() ?? string.Empty;
}));
//do something
I have a string named ds and need to test only if it is null or not. Can I just do the following?
if (ds) { }
It passes a syntax check so I am wondering what conditions this would test as true.
what does the above code do?
String.IsNullOrEmpty will check to see if the string is empty or null.
if( !string.IsNullOrEmpty( ds)) {
// String is valid
}
There isn't a different way:
if (ds == null)
However there are useful methods for assignment operation:
MyClass a;
MyClass b = null;
a = b ?? new MyClass();
This will assign b to a if b is not null, otherwise will assign new MyClass() to a
So to check if a string is null (and only null)
if (ds == null)
otherwise you can use
if (string.IsNullOrEmpty(ds))
or
if (string.IsNullOrWhiteSpace(ds))
If it is a string you might want to use the IsNullOrEmpty method
http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx
It is, of course, short for
result = s == null || s == String.Empty;
Question 1> Should I check NULL in the following case?
public interface INewClass {}
public class NewClass : INewClass {}
public void FunMeA(INewClass obj)
{
NewClass n = (NewClass) obj;
... // Should I check (n == null) here?
// call methods defined inside INewClass (updated from NewClass to INewClass)
...
}
A concrete example,
public void FunMeB(IAsyncResult itfAR)
{
AsyncResult ar = (AsyncResult) itfAR;
... // Should I check (ar == null) here?
// access ar.AsyncDelegate
...
}
Question 2> I just start to transfer to C# from C++.
When coding in C++, I know when the checking should be done.
However, I am totally lost in the C# world. So the question is: is there
a general rule that can tell me when I MUST check for NULL?
Thank you
When doing this:
NewClass n = (NewClass) obj;
There is no point, because if it doesn't cast it will throw an invalid cast exception.
If you have any doubts as to whether or not you can actually cast it, you want to do:
NewClass n = obj as NewClass;
then
if(n != null) ...
The cast you are doing is called a direct cast, where the system will assume that it can be made. the n = obj as NewClass is called an indirect cast and is for those scenarios where you want to tell the program "Hey I think this will work, but if not don't flip out and throw an exception...I'll deal with it if it doesn't work."
Using is vs as in casting.
Depending on which scenario you want one will be better than the other. Technically from a performance perspective as is preferred. .Net will use atomically attempt to cast to the desired type and return null if it's not, where with is it will have to walk the inheritance tree twice to see if it matches that type and then cast it. So in most cases if you want to see if you want to cast and use that type it's better to:
var obj = o as type
if (obj != null)
as opposed to
if(o is type)
{
var obj = (type);
}
If the cast fails, your code will throw an exception.
Use the is operator to see if a cast will work, and as to cast (which will not throw and return a null if the cast fails).
So:
if(obj is NewClass)
{
//Yay, can cast!
}
Or:
NewClass nc = obj as NewClass;
if(nc != null)
{
//Yay!
}
If you want to check for null then you should do
NewClass n = obj as NewClass ;
if (n != null)
{
...
}
But in general you could check for null if that means something to in the context and you can take alternative actions. In most cased, you should just let it throw NullReferenceException rather than swallowing it so you can identify the cause of the null reference faster.
If you do NewClass n = (NewClass)obj you'll get an exception thrown if it doesn't cast properly.
If you want there to be a possibility of it being null, without throwing an exception, you'd want to do NewClass n = obj as NewClass; and then check if n is null.
You can check if a cast is going to work before hand, by using the is operator.
if(obj is NewClass)
Hope this helps.
If the parameter is required, you should always check for null and throw an ArgumentException or ArugmentNullException.
The best way for this parameter check here is:
AsyncResult ar = itfAR as AsyncResult;
if(ar == null)
{
// even better: Use a resource here
throw new ArgumentNullException("Parameter itfAR must not be null and must be of type AsyncResult");
}
I prefer to check to for null before the cast. E.g.
if (obj == null)
{
throw new ArgumentNullException("obj", "The argument must has a value specified");
}
Your are mixing up to issues.
You should always validate arguments to a publicly exposed method. Therefore you sould first do:
public WhateEverMethod(IElement iElement)
{
if (iElement == null)
{
throw new ArgumentNullException(...);
}
}
Once you have validated that element is not null you check if you can perform the cast. You can go two ways essentially:
Element element = iElement as Element;
if (element == null) //cast failed
{
throw new InvalidCastException(...);
}
or
if (!(iElement is Element))
{
throw new InvalidCastException(...);
}
Element element = (Element)iElement;
Does anyone know how can I check whether a session is empty or null in .net c# web-applications?
Example:
I have the following code:
ixCardType.SelectedValue = Session["ixCardType"].ToString();
It's always display me error for Session["ixCardType"] (error message: Object reference not set to an instance of an object). Anyway I can check the session before go to the .ToString() ??
Something as simple as an 'if' should work.
if(Session["ixCardType"] != null)
ixCardType.SelectedValue = Session["ixCardType"].ToString();
Or something like this if you want the empty string when the session value is null:
ixCardType.SelectedValue = Session["ixCardType"] == null? "" : Session["ixCardType"].ToString();
Cast the object using the as operator, which returns null if the value fails to cast to the desired class type, or if it's null itself.
string value = Session["ixCardType"] as string;
if (String.IsNullOrEmpty(value))
{
// null or empty
}
You can assign the result to a variable, and test it for null/empty prior to calling ToString():
var cardType = Session["ixCardType"];
if (cardType != null)
{
ixCardType.SelectedValue = cardType.ToString();
}