Re: Object instantiation in C#
- From: "Dave" <Dave@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 12 Aug 2005 08:49:34 -0700
Aha - got it. I never thought of initialising to null. As I think I've
mentioned before, Jesse Liberty's book doesn't seem to cover null at all.
Many thanks for that.
--
Dave
"Bill Butler" wrote:
> "Dave" <Dave@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
> news:2C4B357F-1521-4CFA-95A5-04F01E8073DB@xxxxxxxxxxxxxxxx
>
> > I have a class MyClass that throws exceptions. It could throw one in the
> > constructor. If it throws I want to call another method on it (maybe
> > request
> > status)
>
> When an UNCAUGHT exception occurs in a constructor, the object is not
> created.
> Also the assignment never takes place ,so your reference will still be
> pointing to whatever it was pointing to before.
>
> Lets use this class for these examples:
>
> class Bad
> {
> public int X;
> public Bad(int x)
> {
> if (x > 3)
> throw new Exception("(x > 3)");
> X = x;
> }
> }
> -------------------------------------------------------
> Example 1: // similar to your example
> public static void Test1()
> {
> Bad bad = null; // This was what the compiler was complaining
> about
> try
> {
> bad = new Bad(5);
> }
> catch (Exception ex)
> {
> if (bad == null)
> Console.WriteLine("(bad == null)");
> else
> Console.WriteLine("bad.X = {0}", bad.X);
> }
> }
> -------------------------------------
> Output:
> (bad == null)
> =====================================================
> Example 2: // Add a loop
>
> public static void Test2()
> {
> Bad bad = null; // This was what the compiler was complaining
> about
>
> for (int i = 0; i < 10; i++)
> {
> try
> {
> bad = new Bad(i);
> }
> catch (Exception ex)
> {
> if (bad == null)
> Console.WriteLine("(bad == null)");
> else
> Console.WriteLine("bad.X = {0}", bad.X);
> }
> }
> }
> -------------------------------------
> Output:
> bad.X = 3
> bad.X = 3
> bad.X = 3
> bad.X = 3
> bad.X = 3
> bad.X = 3
> ==========================================================
>
>
> Hope this Helps
> Bill
>
>
>
.
- Follow-Ups:
- Re: Object instantiation in C#
- From: Bill Butler
- Re: Object instantiation in C#
- References:
- Object instantiation in C#
- From: Dave
- Re: Object instantiation in C#
- From: Bill Butler
- Re: Object instantiation in C#
- From: Dave
- Re: Object instantiation in C#
- From: Bill Butler
- Object instantiation in C#
- Prev by Date: RE: nested using statement or try catch finally?
- Next by Date: Re: Monitoring my c# application with PerfMon
- Previous by thread: Re: Object instantiation in C#
- Next by thread: Re: Object instantiation in C#
- Index(es):
Relevant Pages
|