I need something like this:
string a = "12345"
if (a[5] == null) {
//skip error and continue the cycle
}
So the question is, how to ignore that type of error?
Make an additional length-check like:
if (a.Length >= 6 && a[5] == null) {}
but i think you mean something more like this:
if (a.Length >= 6 && a[5] == char.MinValue) {}
A char cannot be null. It can be '\0', which comes close to a "null".
Regards
Related
I have following code:
var dateFrom = DateTime.Parse(string.Format(string.Format("01.04.{0}", dateProperty.Value.AddYears(-1).Year))
if (object.nullablebool.HasValue ? object.nullablebool.Value : false
&& (string == "V" || string == "N")
&& someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
>> Code
}
I have tested adding .Date or even specifiing exact year from the DateTime struct, but nothing worked.
When executing the code, even if
someDate.Value.Date > dateFrom.Date
equals 1700 > 2018, the code executed as if it was true, even though the debugger says it´s false.
When I removed this part from the condition, following code:
someDate.HasValue && object.SomeOtherDate.HasValue
When I made someDate null, so someDate.HasValue is false, the if statement still executes as true.
What did it fix? Taking these two conditions to another if:
var dateFrom = DateTime.Parse(string.Format(string.Format("01.04.{0}", dateProperty.Value.AddYears(-1).Year))
if (object.nullablebool.HasValue ? object.nullablebool.Value : false
&& (string == "V" || string == "N"))
{
if (someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
>> Code
}
else
{
>> Code
}
}
The code works, but it´s way too ugly. I'm running on Visual Studio 2017 Pro.
Any ideas why it behaves like that? Executing false statements?
Thanks
Your if statement performs different then expected, because it is parsed different as you wouls expect.
object.nullablebool.HasValue ? object.nullablebool.Value : false && ... is parsed as object.nullablebool.HasValue ? object.nullablebool.Value : (false && ...). So if object.nullablebool has a value, thats the result of the condition. To fix this you have to add parenthesis like this:
if ((object.nullablebool.HasValue ? object.nullablebool.Value : false )
&& (string == "V" || string == "N")
&& someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
// if body
}
Let's brush up your code (please, get rid of names like string, object; change them into meanful names):
// You don't want any formatting but a simple constructor
var dateFrom = new DateTime(dateProperty.Value.Year - 1, 4, 1);
// object.nullablebool == true - if object.nullablebool has value and the value is true
if (object.nullablebool == true && (string == "V" || string == "N")) {
// if someDate.Value is null the result will be false
// All we have to do is to propagate the null: ?. in someDate?.Date
if (someDate?.Date > dateFrom.Date && object.SomeOtherDate.HasValue) {
// Code
}
else {
// Code
}
}
This question already has answers here:
Check whether an array is a subset of another
(10 answers)
Closed 8 years ago.
I create a list<string> machineTypes and fill it with data. I want to check to see if the collection contains any combination of strings. My initial plan was to use a for loop, but obviously I can't check multiple indexes in the middle of a for loop.
for (int i = 0; i < machineTypes.Count; i++)
{
if (machineTypes[i] == "W")
//do stuff
if ((machineTypes[i] == "P") && (machineTypes[i] == "W") && (machineTypes[i] == "A") && (machineTypes[i] == "C"))
//do stuff
}
So I'm looking for suggestions as to the best way to do this. I suppose I could use String.Join, but I was wondering if there was a more elegant way.
Perhaps not too elegant - but something like this might help
for (int i = 0; i < machineTypes.Count; i++)
{
int jj=i;
if (machineTypes[i] == "W")
//do stuff
if (jj< machineTypes.Count-4)
if ((machineTypes[jj] == "P") && (machineTypes[jj+1] == "W") && (machineTypes[jj+2] == "A") && (machineTypes[jj+3] == "C"))
//do stuff
}
I just made a new var jj in case you want to increment or alter its value, without altering the i value. Note the if (jj< machineTypes.Count-4) condition checking to see that you can safely use jj+3 as an index.
How should this code be written? I am getting Object reference not set to an instance of an object on if (!query.Keys[i].Contains("ddl"))
string getLink(int toPage)
{
NameValueCollection query = HttpUtility.ParseQueryString(Request.Url.Query);
query["p"] = toPage.ToString();
string url = Request.Path;
int count = query.Count;
for (int i = 0; i < count; i++)
{
if (!query.Keys[i].Contains("ddl"))
url += string.Format("{0}{1}={2}",
i == 0 ? "?" : "&",
query.Keys[i],
query.Keys[i] == "category" ? string.Join("TTT", query.GetValues(i)).Replace(" ", "+") : string.Join(",", query.GetValues(i)));
}
As said, check for nulls. The following is an extreme check but it's better to be safe than sorry.
for (int i = 0; i < count; i++) {
if (query != null &&
query.Keys != null &&
i < query.Keys.Count &&
query.ContainsKey(i) &&
query.Keys[i] != null &&
query.GetValues(i) != null &&
!query.Keys[i].Contains("ddl")) {
url += string.Format(
"{0}{1}={2}",
i == 0 ? "?" : "&",
query.Keys[i],
query.Keys[i] == "category" ? string.Join("TTT", query.GetValues(i)).Replace(" ", "+") : string.Join(",", query.GetValues(i)));
}
}
you can rewrite it as
if (query!=null && query.ContainsKey(i) && !query.Keys[i].Contains("ddl"))
Debug your application; set a breakpoint in the line that causes the exception.
Check on the first iteration if query is null.
Check on each iteration if query.Keys[i] is null
In debug mode, you can also check on what iteration the problem happens (already i==0 or later?). Otherwise, it's hard to tell without knowing what is going on.
I also don't know how you expect that anybody else than you will be able to maintain the code below the if-statement in two years... Simplifying it could make sense.
I don't know your code but it sure looks like you could simply rewrite your for loop
for (int i = 0; i < query.Count-1; i++)
{
}
depending on the purpose of count. You are most likely getting your error due to going past the length of your dictionary. This would fix that issue.
I think there maybe a problem with initialization
NameValueCollection query = HttpUtility.ParseQueryString(Request.Url.Query);
There maybe something wrong with
HttpUtility.ParseQueryString(Request.Url.Query)
part of the code.
Is it possible to convert this if statement into a one line statement ?
if (value != DBNull.Value)
{
dic.Add(columnName);
}
else if (!skipNullValues)
{
dic.Add(columnName);
}
if (value != DBNull.Value || !skipNullValues) dic.Add(columnName);
Use a logical OR:
if (value != DBNull.Value || !skipNullValues)
dic.Add(columnName);
I would keep the addition on a new line for clarity, although for a simple statement like this you're probably alright to drop the curly brackets. You do need to be careful if you try to add more logic in the future though obviously in the branch of the if.
if (!(value == DBNull.Value && skipNullValues))
dic.Add(columnName);
If you edit to include why making it a single line will help you might get a more suitable answer. Here are a few different approaches you could take..
First off, in a single line as you requested:
if ((value != DBNull.Value) || (value == DBNull.Value && !skipNullValues)) { dic.Add(columnName); }
Alternatively you might want to look into using ternary operators if you need something more compact.
var result = (istrue) ? (return valIfTrue) : (return valIfFalse);
More info on ternary operators:
http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx
Most likely (depending on your situation) you should consider creating a method similar to this:
public void AddColumnToDic(object value, string columnName)
bool skipNullValues = false; // todo: read from configuration
if ((value != DBNull.Value) || (value == DBNull.Value && !skipNullValues))
{
dic.Add(columnName);
}
}
and simply call it for every cell value you encounter.
I want to check if two string are of the same length. I tried the following, but it doesn't work.
string passnew = "1233";
string passcnfrm = "1234";
if((passnew.Length&&passcnfrm.Length)>6 ||(passnew.Length&&passcnfrm.Length)<15)
{
// ...
}
Why does it not work? What do I need to change?
if(passnew.Length == passcnfrm.Length &&
passnew.Length > 6 && passnew.Length < 15)
{
// do stuff
}
You are missing some basic syntax lessons. What you write inside of these brackets are conditions. We have unary operators (operating on one thing), binary operators (two) and one tertiary operator (forget about that one).
You cannot construct something like your "boundary test" with those easily.
A possible way:
(passnew.Length > 6) && (passcnfrm.Length > 6)
But you aren't testing if the length is equal anyway, even if you could use a syntax like that. You seem to want to compare if both are longer than 6 chars and shorter than 15 chars. One at 7 and one at 14 would satisfy both conditions..
if(passnew.Length == passcnfrm.Length &&
(passnew.Length < 15 && passnew.Length > 6))
{
// ...
}
Checks both are same length, and either one is more than 6 and less than 15 characters long.
that would be:
if(passcnfrm.Length.Equals(passnew.Length))
{
//do stuff
}
A probably better way to do it is:
if (( passnew != null && passcnfrm != null )
( passnew == passcnfrm )
&& ( passnew.Length > 6 && passnew.Length < 15 ))
{
// do stuff
}
Hides the length check inside the equality check which you'll probably need, it isn't in your question but the variable names make it pretty clear you're doing a password change function there. I added the null check to make sure the length checks don't throw a NullReferenceException, not needed in the example because you assign both manually, but might save some trouble if you're going to convert this to a method later on.
You can use like this:
if (s.Contains(s1[i]))
or:
boolean equalsIgnoreCase(String anotherString);
or use this method:
public static int occurrence(string [] a, string a2)
{
int occ = 0;
for (int i = 0; i < a.Length;i++ )
{
if(a[i].Equals(a2))
{
occ++;
}
}
return occ;
}