String syntax question - c#

What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code:
//Working code
var sep = ", ";
var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName;
//Erronous code
var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName;
The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one.
EDIT: Solved. As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :)

I prefer using string.Format("{0}, {1}",myNewBO[0].LastName,myNewBO[0].FirstName)
Now you can abstract out the format string if you want it be "First Last" for example you can use a different formatting string.
Edit
In response to your actual error, I like others here don't see what is wrong the line of code you have should work so the question becomes: "How are you binding this value to the grid?"
Are you doing this in an Eval() or code behind etc....
One suggestion would to add a ToString(string) method which takes a format string in, then you can bind to the evaluation of the method. And should your business requirements change you just change the formatting string.

string.Join(sep, new string[] {myNewBO[0].LastName, myNewBO[0].FirstName});

I suspect you have something else happening in your code, and you're mistaking where the error is occurring. I can't for the life of me see why those two would behave differently at all. I suggest you log the value after the assignment for both cases - I'm sure you'll find they're the same.

There is really no difference in your two calls, I see no error. What exception are you getting. Joel Coehoorn's answer with regards to String.Join is perfect for what you need.

What error is it throwing? That could tell you alot about why it is crashing.
Your calls both look valid on the surface to me. I would suggest that you make sure LastName and FirstName are strings and not null. To be sure, I guess you could append .ToString() to the end of FirstName and LastName.

Related

Get index of String between unique chars, then remove those chars and apply font to string in C#

so I hope someone here may help me.
My Situation:
I'm using NPOI in C# to export some things to excel. For that, I am also using HSSFRichTextStringto have multiple fonts in one cell.
So, the "cell in need" should look like this:
My Problem here lies in the formating of the "little Numbers" after each article, e.g. 3,20.
To have an entrypoint for using string-comparison, I tried to add ### before the values which worked fine, but I can't figure out how to apply the correct font to the correct substrings (all of them in menuCellContent.
Here's my code so far (I tried a lot of things with stringfunctions, but nothing worked so I think I'll go for the startingpoint so far..), I think it'll make things a little bit clearer (sorry, german here):
var richString = new HSSFRichTextString(menuCellcontent + "\n" + nutrientCellContent);
richString.ApplyFont(0, menuCellcontent.split('###')[0], menuFont);
richString.ApplyFont(menuCellcontent.split('###')[0] + 1, (menuCellcontent + "\n" + nutrientCellContent).Length, nutrientFont);
menuCell.SetCellValue(richString);
but this results in the following output:
which is also not what I want to achieve. I tried for the last few hours to find a string method to generate the desired output, but somehow I always failed. Would be grat if someone here can help me! I think I just have a real knot in my brain..
Best regards,
goide

Comparing Strings in .NET

I am running into what must be a HUGE misunderstanding...
I have an object with a string component ID, I am trying to compare this ID to a string in my code in the following way...
if(object.ID == "8jh0086s)
{
//Execute code
}
However, when debugging, I can see that ID is in fact "8jh0086s" but the code is not being executed. I have also tried the following
if(String.Compare(object.ID,"8jh0086s")==0)
{
//Execute code
}
as well as
if(object.ID.Equals("8jh0086s"))
{
//Execute code
}
And I still get nothing...however I do notice that when I am debugging the '0' in the string object.ID does not have a line through it, like the one in the compare string. But I don't know if that is affecting anything. It is not the letter 'o' or 'O', it's a zero but without a line through it.
Any ideas??
I suspect there's something not easily apparent in one of your strings, like a non-printable character for example.
Trying running both strings through this to look at their actual byte values. Both arrays should contain the same numerical values.
var test1 = System.Text.Encoding.UTF8.GetBytes(object.ID);
var test2 = System.Text.Encoding.UTF8.GetBytes("8jh0086s");
==== Update from first comment ====
A very easy way to do this is to use the immediate window or watch statements to execute those statements and view the results without having to modify your code.
Your first example should be correct.
My guess is there is an un-rendered character present in the Object.ID.
You can inspect this further by debugging, copying both values into an editor like Notepad++ and turning on view all symbols.
I suspect you answered your own question. If one string has O and the other has 0, then they will compare differently. I have been in similar situations where strings seem the same but they really aren't. Worst-case, write a loop to compare each individual character one at a time and you might find some subtle difference like that.
Alternatively, if object.ID is not a string, but perhaps something of type "object" then look at this:
http://blog.coverity.com/2014/01/13/inconsistent-equality
The example uses int, not string, but it can give you an idea of the complications with == when dealing with different objects. But I suspect this is not your problem since you explicitly called String.Compare. That was the right thing to do, and it tells you that the strings really are different!

Replacing backslash in a string

I am having a few problems with trying to replace backslashes in a date string on C# .net.
So far I am using:
string.Replace(#"\","-")
but it hasnt done the replacement. Could anyone please help?
string.Replace does not modify the string itself but returns a new string, which most likely you are throwing away. Do this instead:
myString= myString.Replace(#"\","-");
On a side note, this kind of operation is usually seen in code that manually mucks around with formatted date strings. Most of the time there is a better way to do what you want (which is?) than things like this.
as all of them saying you need to take value back in the variable.
so it should be
val1= val1.Replace(#"\","-");
Or
val1= val1.Replace("\\","-");
but not only .. below one will not work
val1.Replace(#"\","-");
Use it this way.
oldstring = oldstring.Replace(#"\","-");
Look for String.Replace return type.
Its a function which returns a corrected string. If it would have simply changed old string then it would had a void return type.
You could also use:
myString = myString.Replace('\\', '-'));
but just letting you know, date slashes are usually forward ones /, and not backslashes \.
As suggested by others that String.Replace doesn't update the original string object but it returns a new string instead.
myString= myString.Replace(#"\","-");
It's worthwhile for you to understand that string is immutable in C# basically to make it thread-safe. More details about strings and why they are immutable please see links here and here

How to separate name and surname

I have code name and surname put into same string with coma in the middle ,as "JohnSmith"
I need to insert into database to separate
Can you show me how to code that please.
Thanks
vijay
Presumably your asking how to split up a single string where the names are seperated by a comma ','
If that's the case, you can split a string using the Split(char x) method.
Then you can use each part what ever way you want.
string x = "John,Smith";
string [] parts = x.Split(',');
if(parts.Length == 2)
{
string firstName = parts[0];
string secondName = parts[1];
}
Something like that.
Vijay, how about at least trying to google stuff like this by yourself? As in "C# split string"? Hundreds of decent results come up. Heck, there are tons of these examples on SO as well.
Other people can't do your work for you, so how about actually putting in some effort into learning process instead of relying on others to do mundane things for you?
This is easy in most cases, but in a production environment the edge cases kill you. I like the string.split answer, but the incredible variation in how names are formated means more thinking and more code.

Magic strings for converting DateTime to string Using C#

I was greeted with a nasty bug today. The task is pretty trivial, all I needed to do is to convert the DateTime object to string in "yyyymmdd" format. The "yyyymmdd" part was stated in the development doc from the external software vendor. So, I conveniently copied the string from their file and pasted to my code. So I got the next
public string GetDateString(DateTime dateTime)
{
return dateTime.ToString("yyyymmdd");
}
Pretty simple. So simple that I didn't feel like to unit test the method. 20 minutes later, when other parts of my component are done. I started the app to check if things went right. Almost immediately I notice some supposed-to-be date field in my web page is displaying 20091511! This can't be right, there is no 15th month of a year. So, I rushed back to my code to check possible errors. It turns out the that I should have used "yyyyMMdd" instead of "yyyymmdd" when converting DateTime to string.
Admitted, this bug was due to my lack of attention to details. The difference between "mm" and "MM" are cleared stated in all C# references. I still would like to argue that it's pretty easy to overlook the differences if one doesn't work with this kind of tasks everyday.
My question is: Is there a clean(i.e. no magic string) way to do the coverings in one line of code? Thereturn dateTime.Year + "" + dateTime.Month + "" + dateTime.Day; code seems to be working but it's too much like hacking.
Update: Looks like the string format way is the best C# can offer. Maybe I am being brain washed, but I still think this kind of programming style belongs to low-level languages such as c.
String.Format("{0:0000}{1:00}{2:00}", dateTime.Year, dateTime.Month, dateTime.Day);
You could use this instead, I prefer the terse format though. Instead of 00 you can also use MM for specific month formatting (like in DateTime.ToString()).
See here: .NET Custom Date and Time Format Strings
return dateTime.Year.ToString() + dateTime.Month + dateTime.Day;
You don't need to keep adding empty strings, string+number returns string already and addition is interpreted from left to right.
Do note that that line doesn't return what you think it does, what you really want is:
return dateTime.Year.ToString("0000") + dateTime.Month.ToString("00")
+ dateTime.Day.ToString("00");
If that format string bugs you that much, at least make sure it is in one place. Encapsulate it e.g. in an extension method:
public string ToMyAppsPrefferedFormat(this DateTime date) {
return date.ToString("ddMMyyyy");
}
Then you can say date.ToMyAppsPrefferedFormat()

Categories