clarifying

S

smith flyers

static void Main(string[] what) { string test="testing 1 2 3";
test.Replace("testing", "test"); } // why this doesn't replace the word
"testing" ?

when using "try" can i use multiple "block catch" ? // i tried but can't
, this is allowed in java right, how about C#?
ex. catch(exception e) {} catch(FormatException){}


thank you for clarifying
 
W

William Ryan

Change your proc like this so that you assign test = test.Replace


static void Main(string[] what) {
string test="testing 1 2 3";
test = test.Replace("testing", "test"); //change this line.
} // why this doesn't replace the word "testing" ?

You can and often should have multiple catch blocks. Remember though that
you need to go from most precise to most broad.

If you tried this

catch(System.Exception e){}
cathc(System.FormatException f){}

The compiler will yell about unreachable code. Why? B/c the First catch
block will grab any exception, so if a FormatException was thrown, it would
get caught in the first catch, not the second. If you flip them around, all
will be well. This is important b/c in VB.NET, it wont' bark at you and
could inject subtle logic errors ---and even outside of VB.NET, remember
that the Exceptions are processed in order - they don't skip to the
corresponding handler .

HTH,

Bill
 
H

Habib Heydarian [MSFT]

In .NET, strings are immutable meaning that you cannot change their value.
All the operations on a string result in a new string. In this case,
String.Replace() returns a new string with the word "testing" replaced. You
can see it from this example where newValue contains the new string.

public static void Main()
{
string test="testing 1 2 3";
string newValule = test.Replace("testing", "test"); // why this doesn't
replace the word "testing" ?
}

Try using System.Text.StringBuilder instead, which does exactly what you
want:

public static void Main()
{
System.Text.StringBuilder sb = new StringBuilder("testing 1 2 3");
sb.Replace("testing", "test");
string newValue = sb.ToString();
}

Yes, you can have multiple catch blocks when using try. Here's an example:

public static void Main()
{
try
{
FileStream fs = File.Open(@"C:\Foo.txt", System.IO.FileMode.Open);
}
catch (ArgumentException e)
{
}
catch(FileNotFoundException e)
{
}
catch(IOException e)
{
}
finally
{
}
}

HabibH.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top