Thanks Arjay,
It is good to learn from you below that we only need to return a reference variable, no need to explicitly allocate new instance in using statement, right?
Quote:
Originally Posted by Arjay
regards,
George
Printable View
Thanks Arjay,
It is good to learn from you below that we only need to return a reference variable, no need to explicitly allocate new instance in using statement, right?
Quote:
Originally Posted by Arjay
regards,
George
Thanks JonnyPoet,
For your code sample, there is an issue that you modified the code of Dispose method which handles exception itself.
Suppose in many cases we use libraries which does not allow us to change the code.
I have made imprvement of your code to never depends on changing code of Dispose method, and catch the exception inside using block before the automatically generated finally block by using block.
Here is my code, any comments?
Code:using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
using (MyObject myobj = new MyObject())
{
try
{
Console.WriteLine(myobj.ToString());
throw new MyException("inner exception");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
class MyException : ApplicationException
{
public MyException(string message)
: base(message)
{
}
}
class MyObject : IDisposable
{
public virtual void Dispose()
{
try
{
Console.WriteLine("Disposed ");
throw new MyException("Disposed exception. ");
}
catch
{
Console.WriteLine("Disposed Error Handled");
}
}
public override string ToString()
{
return "This is MyObject";
}
}
}
}
regards,
George
Incorrect. What do you think Message.CreateMessage(...) is doing?Quote:
Originally Posted by George2
And from where do you think will Createmessage take the reference From a reference pool ? :eek: from Heaven ? :sick:Quote:
Originally Posted by George2
Please George! ;) dont expand the thread with quetion without using a bit of own research...
Thanks Arjay and JonnyPoet,
To show my point, here is my code. My question is, it is not a must to using "new" to create instance in "using" block?
Code:static void Main(string[] args)
{
StreamWriter sw = new StreamWriter ("a.txt");
using (sw)
{
sw.WriteLine("I am fine");
}
return;
}
Quote:
Originally Posted by JonnyPoet
regards,
George
George,
You have been repeated told that...
Is EXACTLY the same asCode:using ( identifier /*part1*/)
{
/*part2*/
}
Nothing MORE, nothing LESS. It is pruely syntactic "Sugar"..Sweet to read, but provides NO functional value over the alternative.Code:try
{
/*part1*/
/*part2*/
}
finally
{
identifier.Dispose();
}
Thanks TheCPUWizard,
Your reply is clear. Sorry, it is my misunderstanding before that I think we have to use new something inside the using block. :wave:
Quote:
Originally Posted by TheCPUWizard
regards,
George