Returning a new value - c#

I have write a function but this function still returns me the old string in stead of the new one. I don't know how to return a new string when you did something with the old one
By example:
public string TestCode(string testString)
{
// Here something happens with the testString
//return testString; <-- i am returning still the same how can i return the new string //where something is happened with in the function above
}

// Here something happens with the testString
Make sure what ever you are doing with the string, you are assigning it back to testString like.
testString = testString.Replace("A","B");
since string are immutable.
I assume you are calling the function like:
string somestring = "ABC";
somestring = TestCode(somestring);

Simply make sure you assign the new string value to a variable (or the parameter testString). For example, a very common mistake here is:
testString.Replace("a", ""); // remove the "a"s
This should be:
return testString.Replace("a", ""); // remove the "a"s
or
testString = testString.Replace("a", ""); // remove the "a"s
...
return testString;
The point is: string is immutable: Replace etc do not change the old string: they create a new one that you need to store somewhere.

String is immutable (i.e. cant be changed). You have to do like this
myString = TestCode(myString)

Related

Deleted words from a string

Is there any possibility to delete specific words from a string? For exempla
string x ="documents\bin\debug" and I want to delete "\bin\debug".
Use String.Replace():
string x = #"documents\bin\debug";
string desiredString = x.Replace(#"\bin\debug", String.Empty);
Note: The key thing here is that you have to assign the string returned by the Replace() function to a variable. (From your comment on the question, it is the problem). This can either be another variable (as in the above example) or the same variable:
string x = x.Replace(#"\bin\debug", String.Empty);
Implicitly, not assigning the return value to a variable (or using the former way) will keep the value of x, unchanged, which is the exact problem you're facing. Hope it helps :)
Use string replace
string x = #"documents\bin\debug";
string nestring = x.Replace(#"\bin\debug", "");
Console.WriteLine(nestring);

The console output is visible, but the richTextBox.Text is empty

I have a function that is giving me a Console.Writeline output, but it's not writing the information to my richTextBox.
public static void FindFeatureSecurityEsc(string[] actualFontName, string displayFontName, string dragDropSourceData, string outputData)
{
//Create a list to hold all the fonts
var listOfDisplayFonts = new List<string>();
string[] arrayOfDisplayFonts = listOfDisplayFonts.ToArray();
//Display font name for each font that exists in the dragdrop rich text box.
if (dragDropSourceData.Contains(actualFontName[0]) || dragDropSourceData.Contains(actualFontName[1]) || dragDropSourceData.Contains(actualFontName[2]))
{
//If the font doesn't already exist in the output textbox.
if (!outputData.Contains(displayFontName))
{
//Add font to the output textbox.
listOfDisplayFonts.Add(displayFontName);
foreach (string s in listOfDisplayFonts)
{
//Add strings from list to text box.
outputData += string.Join(Environment.NewLine, s) + "\n";
}
//Clear fonts from the list (They've already been added to the textboxes).
listOfDisplayFonts.Clear();
}
}
Console.WriteLine(outputData);
}
In this example, outputData is equal to richTextBox1.Text (the last parameter). When I am using this function in my Main.cs, these are the parameters.
FontFinder.FindFeatureSecurityEsc(EscapeSequence.fontEsc12pt, EscapeSequence.fontDispName, dragDropRichTextBox1.Text, richTextBox1.Text);
Why is it that the Console.Writeline is giving me the proper output, but richTextBox1.Text remains empty? I know the function is proper, because if I call it directly from my Main.cs (and fill the actual parameter values into the function), it works fine. This is mostly an educational exercise to help me learn.
You're passing the text string of richTextBox1 to the method. The statement outputData += string.Join(Environment.NewLine, s) + "\n"; would concatenate text and create a new string (a string is immutable) but the original text string that was passed remains the same.
You need to assign back the result to richTextBox1:
richTextBox1.Text = FontFinder.FindFeatureSecurityEsc(EscapeSequence.fontEsc12pt,
EscapeSequence.fontDispName, dragDropRichTextBox1.Text, richTextBox1.Text);
Of course in this case you should change the method's return type from void to string and return outputData; at the end.
In this example, outputData is equal to richTextBox1.Text (the last parameter).
It might have the same string value when you start, but it is not the same variable.
You pass in outputData.
FindFeatureSecurityEsc(string[] actualFontName, string displayFontName, string dragDropSourceData, string outputData)
Then you modify it a bunch, and finally write it to the console.
Console.WriteLine(outputData);
You never assign your new outputData back to any control.
The outputData that you passed in is a different one than the final one you write to the console, because strings are immutable. That's a fancy way of saying you don't modify the original string, but rather you create a new one.
To solve the problem, assign outputData to the control. You can do that within the function you posted if it has access to the control, or it can return outputData back instead of having a void return type.
Quick fix:
At the end of your function, do this (obviously changing the return type to string from void as well):
return outputData;
So your function becomes:
public static string FindFeatureSecurityEsc(string[] actualFontName, string displayFontName, string dragDropSourceData, string outputData)
{
// everything the same as before...
return outputData;
}
Then you can call it like this:
richTextBox1.Text = FontFinder.FindFeatureSecurityEsc(EscapeSequence.fontEsc12pt,
EscapeSequence.fontDispName, dragDropRichTextBox1.Text,
richTextBox1.Text);
Strings are immutable. That means whenever you concatenate or do any other kind of string manipulation you are actually creating a new string. Your control's .Text property is still pointing to the old string so it won't "see" any of the changes.
The other approach here would be to change your function to take the control instead of the just the string:
public static void FindFeatureSecurityEsc(string[] actualFontName, string displayFontName, string dragDropSourceData, RichTextBox outputDataCtrl)
{
var outputData = outputDataCtrl.Text;
// rest of your function as before
outputDataCtrl.Text = outputData;
}
Which approach is better is up to you.
Looks like you are only using the richTextBox1.Text to display the output, since you are passing it by value. Hence the Console.Writeline output is correct. You would be able to get the result in the richTextBox.Text if you pass it by ref. That way you don't even have to change the return type of your method and assign it back to the control's text.

Replace value from a variable to another value

i have a controller where i read a html file into a variable.
After read it i replace some values from the variable to other values,
but the problem is that nothing happend.
What is wrong here ?
can someone give me a hand with this?
string path = "/mypath/myfile.html";
string s = System.IO.File.ReadAllText(path);
s.Replace("#%a%#","hi");
s.Replace("#%b%#","yo");
s.Replace("#%c%#","asdfasdf");
s.Replace("#%d%#", "http://www.google.com");
Strings are immutable - you should assign result of replacement to your string. Also you can chain replacement operations like this:
string s = System.IO.File.ReadAllText(path)
.Replace("#%a%#","hi")
.Replace("#%b%#","yo")
.Replace("#%c%#","asdfasdf")
.Replace("#%d%#", "http://www.google.com");
Just keep in mind - all string operations (like Replace, Substring etc) will create and return new string, instead of changing original. Same implies to operations on DateTime and other immutable objects.
UPDATE: You can also declare dictionary of your replacements and update string in a loop:
var replacements = new Dictionary<string, string> {
{ "#%a%#","hi" }, { "#%b%#","yo" }, { "#%c%#","asdfasdf" } // ...
};
string s = System.IO.File.ReadAllText(path);
foreach(var replacement in replacements)
s = s.Replace(replacement.Key, repalcement.Value);
A string is immutable. Basically, an object is immutable if its state doesn’t change once the object has been created. Consequently, a class is immutable if its instances are immutable.
string path = "/mypath/myfile.html";
string s = System.IO.File.ReadAllText(path);
s = s.Replace("#%a%#","hi");
s = s.Replace("#%b%#","yo");
s = s.Replace("#%c%#","asdfasdf");
s = s.Replace("#%d%#", "http://www.google.com");

How to use myString.PadLeft?

Why doesn't this work ?
string myString = "test";
int i = myString.Length; // i = 4
myString.PadLeft(5, '_'); // "myString" is should be equal to "_test", but it still "test"
i = myString.Length; // i = 4 (should be 5)
Most string methods don't change string itself, but return new string, so use it like this:
myString = myString.PadLeft(5, '_');
EDIT: Ahh yes, all methods. I thought about methods that don't return string and somehow ended with not entirely true sentence.

string.Replace (or other string modification) not working

For the following code, I can't get the string.Replace to work:
someTestString.Replace(someID.ToString(), sessionID);
when I debug and check parameters they have values I expect - i.e. someID.ToString() got "1087163075", and sessionID has "108716308" and someTestString contains "1087163075".
I have no idea why this would not work change someTestString
Complete sample:
string someTestString =
"<a href='myfoldert/108716305-1.jpg' target='_blank'>108716305-1.jpg</a>"
someTestString.Replace("108716305", "NewId42");
the result (in someTestString) should be this:
"<a href='myfoldert/NewId42-1.jpg' target='_blank'>NewId42-1.jpg</a>"
but it doesn't change. The string for someTestString remains unchanged after hitting my code.
Strings are immutable. The result of string.Replace is a new string with the replaced value.
You can either store result in new variable:
var newString = someTestString.Replace(someID.ToString(), sessionID);
or just reassign to original variable if you just want observe "string updated" behavior:
someTestString = someTestString.Replace(someID.ToString(), sessionID);
Note that this applies to all other string functions like Remove, Insert, trim and substring variants - all of them return new string as original string can't be modified.
someTestString = someTestString.Replace(someID.ToString(), sessionID);
that should work for you
strings are immutable, the replace will return a new string so you need something like
string newstring = someTestString.Replace(someID.ToString(), sessionID);
You can achieve the desired effect by using
someTestString = someTestString.Replace(someID.ToString(), sessionID);
As womp said, strings are immutable, which means their values cannot be changed without changing the entire object.

Categories

Resources