using a method invoker in an if statement - c#

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

Related

Return null to avoid unknown exceptions from a method in C#

I have the following method that opens a Excel workbook and returns it to be used in another method.
private Excel.Workbook openWorkbook()
{
// Get excel file path returns the file path of the excel workbook if it exists, otherwise returns null.
List<string> filePaths = getExcelFilePath();
if (filePaths != null)
{
return excel.Workbooks.Open(filePaths[0]);
}
return null;
}
As you can see, I'm returning null to avoid a try-catch for a non-exixtent workbook when I call this from another method. Is it bad practice to do this. I do a similar thing in the following method which is supposed to return a list:
private List<string> getSOsToDelete()
{
// rawData is private variable in the class. If the workbook was not open this worksheet is set to null in another method similar to openWorkbook() above.
if (rawData != null)
{
List<string> ToDeleteSOs = new List<string>();
for (int i = rawData.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row; i > 1; i--)
{
if (rawData.Cells[i, 7].Value2.ToString() != "B2B" || rawData.Cells[i, 7].Value2.ToString() != "" || rawData.Cells[i, 8].Value2.ToString() != "Trns-Inc" || rawData.Cells[i, 8].Value2.ToString() != "")
{
string SONumber = rawData.Cells[i, 3].Value2.ToString();
ToDeleteSOs.Add(SONumber);
}
}
return ToDeleteSOs;
}
return null;
}
If not so, what is the best way to write methods like these? For part 2 I guess I could return an empty list and check for length. I'm not sure which is better. However, for first method, I'm really not sure what to return if the file doesn't exist.
I think there is no hard and fast rule for this. But I would return null from first method as returning a null where there is no workbook seems meaning full as null represent no object but from second method empty list would be a batter option as with list we used to use Count before using it instead of null or iterate over list etc. This also goes with convention like ToList will return list of zero elements instead of returning null.
Return null to avoid unknown exceptions from a method in C#
There could be different way to tell the caller method that error occurred in called method and exception is one of those and widely adopted. You can document the method to tell when kind of exception are expected from the method. Lets look at documentation of String.Substring Method (Int32, Int32) on MSDN. The documentation mentions that this method could through ArgumentOutOfRangeException when startIndex plus length indicates a position not within this instance, or startIndex or length is less than zero, MSDN

Assign a variable and check value?

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

How to handle a method that might return null and generate a System.NullReferenceException

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.

Null Exception handling in foreach loop

I am having the list X with some string and null value . I am iterating the foreach loop to bind the value to the textbox. If I get any null values in my list X the foreach loop get terminated and getting the null exception how to handle it.
I am checking the condition inside the foreach loop, but I think it's not correct logically.
SPList _listObj = web.Lists[new Guid(listID)];
SPListItem item = _listObj.GetItemById(Convert.ToInt32(itemID));
foreach (SPField field in _listObj.Fields)
{
if (field.Title != Null)
{ //do some code}}
Try below code:
foreach(var x in Lists.Where(x => x.fiels != null))
{
}
Why don't you use it like this with null-coalescing operator
foreach (var item in feeList ?? new List<FeeBusiness>())
{
// your code
}
The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
That code looks pretty suspicious to me.
Firstly, do you really have a list of lists? If so, I'd imagine you have to iterate over each element in the inner list as well:
foreach(List list in Lists)
{
foreach (var x in list)
{
if (x.fields != null)
// blah
else
// blah
}
}
Secondly, are you sure that the Lists variable doesn't contain any nulls? Possibly it's actually x which is null, and that's the cause of your Null Reference Exception:
foreach(List x in Lists)
{
if (x != null && x.fields != null)
// blah
else
// blah
}
The code provided is not correct. I suppose you want to check X for Null in foreach loop. If this is logically correct or not, instead only you may know as logic goes beyond the code provided and depends on where you actually use it.
I personally don't find nothing bad to check for nulls in foreach loop.
You also, for example, can use Linq to query first for Null values and after Non Null values. The matter of design choice.
Regards.
List x in Lists? You probably mean to do:
foreach(string x in listvar){
if(x != null)
// do something
}
And are the strings actually null or just empty? That is a difference.
foreach(string x in listvar){
if(x != "")
// do something
}
I suspect that the problem is in your incorrect implementation of the foreach loop which causes to pop null errors as the objects inside the loop do not exist.
string delimitedvalues = null;//"11,22,33";
foreach(var str in (delimitedvalues?? string.Empty).split(','))
{
string testvalue = "Test Value" + str;
}
Hope the above construct is useful!
You have to make sure that your object you are getting doesn't come back as null (your list, _listObj) before you ever iterate its fields. Even if you are certain the GUID you are passing in matches the list you are trying to get, you should be checking that object for being null, and checking for the number of fields, and if you get an item for the ID you are passing in:
SPList _listObj = web.Lists[new Guid(listID)];
if (_listObj != null) // do we have a list object?
{
if (_listObj.Fields.Count > 0) // do we have list columns on the list?
{
SPListItem item = _listObj.GetItemById(Convert.ToInt32(itemID));
if (item != null) // did our item ID get a hit?
{
foreach (SPField field in _listObj.Fields)
{
if (field.Title != null) // need lower case null, here
{
//do some code
}
}
}
}
}

C#: Use of unassigned local variable, using a foreach and if

I have this following code:
I get the error, "Use of un-Assigned Local variable"
I'm sure this is dead simple, but im baffled..
public string return_Result(String[,] RssData, int marketId)
{
string result;
foreach (var item in RssData)
{
if (item.ToString() == marketId.ToString())
{
result = item.ToString();
}
else
{
result = "";
}
}
return result;
}
Initialize result when you declare it. If the collection is empty neither of the branches of the if statement will ever be taken and result will never be assigned before it is returned.
public string return_Result(String[,] RssData, int marketId)
{
string result = "";
foreach (var item in RssData)
{
if (item.ToString() == marketId.ToString())
{
result = item.ToString();
}
}
return result;
}
If there are no items in RssData, then result will have never been set, and thus invalid.
Either initialize result (e.g., string result = null;) or consider that in your design by checking for emptiness, and setting or returning a failure state in that scenario.
That is because the compiler can't know that there always are any items in RssData. If it would be empty, the code in the loop would never be executed, and the variable would never be assigned.
Just set the variable to null when you create it, so that it always has a value:
string result = null;
If RssData has zero items, the loop will not run, leaving result undefined. You need to initialize it to something (e.g. string result = "";) to avoid this error.
Change your line from
string result;
To
string result = string.Empty; // or null depending on what you wish to return (read further)
The compiler is just saying "Hey, you are using result and it has not been assigned yet!". This even ocurrs when you are assigning it for the first time, if you're not doing so in the initial instantiation.
You will also want to consider how you need to handle your code if you return an empty string, due to your array argument being passed in empty. You could choose to return an empty string, or a null value. This is just a behaviorial decision.
This can happen for all variable types as well.
For collections and objects, initialize using new.
eg. List<string> result = new List<string>();

Categories