C# Replace is causing Object Reference Not Found error - c#

using "Replace" on the string clientNameStr causes an "Object Reference Not Found" error.
// Get client name
clientName = currentUser.GetValue("ClientName");
string clientNameStr = (string)clientName;
string clientURLStr = string.Empty;
clientURLStr = clientNameStr.Replace(' ', '-');
// clientURLStr = "ST9215-Stanic-Parts-Ltd";
If I substitute in the commented out string (and comment out the existing one) it works fine, so it must be something to do with the replace function, but what? Have tried it with both " and ' quote marks, to the same result.
Any help would be greatly appreciated.
Thanks, Oli.

That basically shows that currentUser.GetValue("ClientName") is returning a null reference1.
We can't tell what currentUser.GetValue("ClientName") does, but there are two options:
It's correctly returning null, and you should handle that
It shouldn't return null, and you need to fix it (possibly to throw an exception if it encounters this situation)
1 It's possible that it's returning a non-null reference and using a user-defined conversion to string in the next line which returns null - but unlikely. We can't tell for sure because we don't know the type of the clientName .

Probably clientName (and thus clientNameStr) is null. You cannot call methods on the null object, even if you know that it should be a string.

It's possible that currentUser.GetValue("ClientName") is returning null, thus throwing an error when trying to execute the Replace.
Better coding would be
clientName = currentUser.GetValue("ClientName");
string clientNameStr = clientName ?? "";
string clientURLStr = clientNameStr.Replace(' ', '-');

Related

Difference between "" (Empty String) and isNot Nothing?

I am working on a condition where I have to validate whether the argument is empty or not. Lets assume that argument is Email. I have to check whether the inwards argument Email is empty or not. I can do it in several way but I am not sure which one to proceed with.
I am thinking to check from following statement:
1.Email = "" to check if email is empty string or not.
2. Email isNot Nothing
I wanna know the difference of these two functionality. If there are more function or argument related to validating empty string, You can write that too.
Thanks.
String is a reference type, which means it can have a null reference
Eg
string myString = null;
It can also be empty, which is to say, there is a reference to it, and it has 0 character length
Eg
string myString = "";
// or
string myString = string.Empty;
And just for completeness, it can also have white space
Eg
string myString = " ";
You can check for null like so
if(myString == null)
You can check for empty
if(myString == "")
// or
if(myString == string.Empty)
You can check for both, not null and not empty
if(myString != null && myString != string.Empty)
You could use Null conditional Operator with Length to check both is not null and not empty
if(myString?.Length > 0)
Or you can use the built in string methods, to make it a little easier
String.IsNullOrEmpty(String) Method
Indicates whether the specified string is null or an empty string
("").
if(string.IsNullOrEmpty(myString))
String.IsNullOrWhiteSpace(String) Method
Indicates whether a specified string is null, empty, or consists only
of white-space characters.
if(string.IsNullOrWhiteSpace(myString))
Note : It's worth noting, that IsNullOrWhiteSpace generally more robust when checking user input
Actually in C# string.Empty is equivalent to "". See String.Empty
Best way to check for Empty or Null strings is:
string.IsNullOrEmpty(Email) or you can use string.IsNullOrWhiteSpace(Email) to additionally check for white spaces.
if(!string.IsNullOrEmpty(Email))
{
// Good to proceed....
}
You should not use IsNot nothing with reference type variable. Instead, Use string.IsNullOrEmpty(Email) together with String.IsNullOrWhiteSpace(Email) while you need to validate email.

Code returning false on equal compare?

Problem I currently have:
My server returns data back to the client, this includes a name. Now I want the client to grab this name and compare it. However for the past 3 hours I am stuck at this problem and I dont want to cheap fix around it.
My server returns a value and then a name, ex: random23454#NAMEHERE
I split the value using:
string[] values = returndata.Split('#');
And then I am doing:
if (textBox3.Text == values[1]) {
MessageBox.Show("equal");
}
However, the problem here is. I cant get it to be equal, I tried other methods but it just dont display equal.
What I have done:
Print textBox3.Text to a textbox and print values[1] to a other textbox and compared with my eye and mouse (Using invoke due to threading).
Used the .Trim() function
Using the .ToString() on values[1] (Just for the hell of it)
Assigned them both to a complete new string, trimmed them and compared them
Dragged the comparing outside the thread using:
this.Invoke((MethodInvoker)delegate()
{
outside(name);
});
and perform the same check.
My code:
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
if (readData.Contains("#") && readData.Contains("random"))
{
string[] values = returndata.Split('#');
string name = values[1].Trim();
if (textBox3.Text == name)
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
this.Invoke((MethodInvoker)delegate()
{
outside(name);
});
}
What else can I do? I just dont understand that it is not equal..
Thanks in advance.
The data you're getting back from the server could be an array of bytes. Try converting the response to a string first before splitting. Also try printing the response (or the response's type) to console to see what you get before going any further.
Also make sure the length of each string is the same. Maybe give utf-8 a try instead of ASCII? Like so:
System.Text.Encoding.UTF8.GetString(inStream);
string name = values[1].Trim();
I think you want values[2] here. The way I read the documentation for Split, the element at index 1 will be the (blank) separator indicator.

.Trim() when string is empty or null

I'm receiving some data from the client in the form of json.
I'm writing this:
string TheText; // or whould it be better string TheText = ""; ?
TheText = ((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());
If the variable that's being parsed from json comes back empty, does this code crash when I call the .Trim() method?
Thanks.
You can use elvis operator, also known as "null-conditional-operators":
GetNullableString()?.Trim(); // returns NULL or trimmed string
More info: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators
If the serializer returns an empty string, Trim will do nothing.
If the serializer returns null, you will get a NullReferenceException on the call to Trim.
Your code would be better written (as far as initialization is concerned) like this:
string theText =
((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());
There is no point in declaring and initializing the variable and the immediately assigning to it.
The following would be safest, if you don't know what the serializer might return:
string theText = ((serializer.ConvertToType<string>(dictionary["TheText"])));
if(!string.IsNullOrEmpty(theText))
{
theText = theText.Trim();
}
Calling Trim() on an empty string will result in an empty string. Calling Trim() on null will throw NullReferenceException
If you have a few fields you wish to trim but your getting exceptions for those records that have nulls in certain fields, then writing a quick extension method will be the easiest method:
public static class ExtensionMethods
{
public static string TrimIfNotNull(this string value)
{
if (value != null)
{
return value.Trim();
}
return null;
}
}
Sample example of use:
string concatenated = String.Format("{0} {1} {2}", myObject.fieldOne.TrimIfNotNull(), myObject.fieldTwo.TrimIfNotNull(), myObject.fieldThree.TrimIfNotNull());
Some basic techniques to check strings against null before you trim:
(mystring ?? "").Trim()
The "null coalescing operator" ?? will return the first operand. Only when this operand is null, the second operand will be returned (as a kind of default value).
The above example will return an empty string if mystring is null.
mystring?.Trim()
The "null conditional operator" ? will short cirtuit a chain of operations in dot-notation. If the operand is null, the following operations will not be executed and null will be returned.
The above example will return null if mystring is null.
if( string.IsNullOrWhiteSpace(mystring) ) { ... }
the IsNullOrWhiteSpace() method may replace trimming if you actually want to check if there is real content in mystring. It returns true if the operand is null, empty, or nothing but whitespace characters.
As suggested in some of the comments, you may now use c# 6 Null-conditional operators with this syntax:
string TheText = (serializer.ConvertToType<string>(dictionary["TheText"]))?.Trim();
Documentation: https://msdn.microsoft.com/en-us/library/dn986595.aspx
No, it would not be better to initialize TheText to "". You're assigning to it right afterwards.
No, it won't crash – Trim() works just fine on an empty string. If by "empty" you mean that it can be null, then yes, it will crash; you could have null remain null with a null-conditional call:
string TheText =
serializer.ConvertToType<string>(dictionary["TheText"])?.Trim();
You can use the null-safe operator trim of org.apache.commons.lang
StringUtils.trim(stringOrNull)
You can use this code as beblow
string theText = (((serializer.ConvertToType<string>(dictionary["TheText"])))+ string.Empty).Trim();
Recently I had to check a string if it is null, empty or whitespace using just one if condition and for that I found out that you can add "" to a null string to make it non null.
string test = GetStringFromSomeWhere(); // null
if(string.IsNullOrEmpty(test.Trim())) { return true; } // Exception
So I did this instead
string test = GetStringFromSomeWhere() + ""; // ""
if(string.IsNullOrEmpty(test.Trim())) { return true; } // true

Specified cast is not valid exception in ms access query using C#

hey guys m having this wierd exception of cast though my datatypes are correct in db:
string sql =
string.Format(
#"select aim_network_id,aim_network_name,oxinetwork_id,pack_id,pack_name,p_face_value,pm_prefix from Operator where aim_network_id='{0}'",
gridbackOffice["aim_network_id", gridbackOffice.CurrentCell.RowIndex].Value);
OleDbCommand getSelectedGridDatecmd = new OleDbCommand(sql, conn);
OleDbDataReader reader = getSelectedGridDatecmd.ExecuteReader();
while (reader.Read())
{
txtAimNetworkID.Text = reader.GetString(0);
txtAimNetworkName.Text = reader.GetString(1);
txtPARNetworkID.Text = reader.GetString(2);
txtPARFaceValue.Text = reader["p_face_value"].ToString();
//in above line if i'm doing this `reader.GetString(5)` then i'm getting specified cast exception and that to randomly i.e some time it works fine and suddenly sometime gives this exception
txtPARPackID.Text = reader.GetString(3);
txtPARPackName.Text = reader.GetString(4);
txtPARPMPrefix.Text = reader["pm_prefix"].ToString();
}
I'm little bit confused if m using this reader["p_face_value"].ToString() then my code is running very smoothly but whats the issue with using this reader.GetString(5) , according to me both method return string, nebody had faced this error b4 ?
....Error is at 4th and 7th line in while loop.
Exception:Specified cast is not valid (InvalidCastException unhandled)
According to MSDN, OleDbDataReader.GetString() does not perform any conversions before attempting to cast to a string - therefore the data retrieved must already be a string.
If there is a chance that the value in that column could be null, the docs suggest that you should check if the value is null first:
if ( !reader.IsDBNull(5) ) {
txtPARFaceValue.Text = reader.GetString(5);
}
Calling reader["p_face_value"] on a null value returns DBNull - and when you call ToString() on DBNull, you get an empty string.
From MSDN:
No conversions are performed;
therefore the data retrieved must
already be a string.
If the column is not a string type, you'll need to use the .ToString() method to convert it.
What is the datatype of p_face_value in your database?
Based on the error description given it seems that this is not a string type, so when you call:
reader.GetString(5)
the code errors out as it cannot convert whatever type it is to a string. The .ToString() method will work as this does not use a cast.
You should use GetString only when the column is a string-equivalent type in the database (like varchar), in your case "p_face_value" seems to be a numeric type, therefore it cannot simply convert it to a string.
The way you're doing it right now is the right way.

Convert String to Integer [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
how can I convert String to Int ?
Hi,
I have the following problem converting string to an integer:
string str = line.Substring(0,1);
//This picks an integer at offset 0 from string 'line'
So now string str contains a single integer in it. I am doing the following:
int i = Convert.ToInt32(str);
i should be printing an integer if I write the following statement right?
Console.WriteLine(i);
It compiles without any error but gives the following error on runtime:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
Any help please?
Rather than using Convert.ToInt32(string) you should consider using Int32.TryParse(string, out int) instead. The TryParse methods are there to help deal with user-provided input in a safer manner. The most likely cause of your error is that the substring you are returning has an invalid string representation of an integer value.
string str = line.Substring(0,1);
int i = -1;
if (Int32.TryParse(str, out i))
{
Console.WriteLine(i);
}
FormatException
value does not consist of an optional
sign followed by a sequence of digits
(0 through 9).
The exception that is thrown when the
format of an argument does not meet
the parameter specifications of the
invoked method.
You can use Int32.TryParse if you don't want to generate an exception like this.
Int32.TryParse: Converts the string representation of
a number to its 32-bit signed integer
equivalent. A return value indicates
whether the operation succeeded.
It's entirely possible there is some whitespace in there. Try running something akin to trim() (I'm not sure what language you're in) that will strip the white space. Also, try printing out the string to make sure you actually have the right part of it. We've all done that :)
It's likely that your input is not a valid format. Try this instead. If the number is not valid, it should output an error.
Keep in mind that the string should consist of an optional sign followed by a number.
string line = "23"; // or whatever.
string str = line.Substring(0,1);
int i = 0;
if (Int32.TryParse(str, out i)) {
Console.WriteLine(i);
} else {
Console.WriteLine ("Error converting '" + line + "', '" + str + "'.");
}
One thing you may be seeing is the user entering "-1" for example. If you do the substring(0,1) on that, you'll only get "-" which isn't really valid.
Are you sure that the value returned in str is an int, set a debug point if your using visual studio. Ive got a feeling your problem maybe that your not actually returning an integer. Try:
line.Trim().Substring(0,1);
This will remove any whitespace.

Categories

Resources