beginner C# constructor, how to return null ?

  • Thread starter Thread starter Romain TAILLANDIER
  • Start date Start date
R

Romain TAILLANDIER

Hi group,

I have a class MyClass.

MyClass a = new MyClass();

during the constructor, the initialisation could abort. when it is happend,
I need that new return null.
how can i do that ??

thank you
ROM
 
Romain TAILLANDIER said:
I have a class MyClass.

MyClass a = new MyClass();

during the constructor, the initialisation could abort. when it is happend,
I need that new return null.
how can i do that ??

You can't. Instead, you need to throw an exception.
 
Throw an exception and in the Catch, set the object to null explicitly.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

**********************************************************************
Think Outside the Box!
**********************************************************************
 
You can't, but you can throw an exception and put the "new" statement inside
a try/catch. Another option is the "factory" model, where instead of

MyClass a = new MyClass();

you would do

MyClass a = MyClass.Create();

and implement a static method called Create in your class. Example:

public class MyClass
{
private MyClass()
{
// constructor is private so nobody can use "new"
}

public static MyClass Create()
{
MyClass temp = new MyClass();
// initialize your object here
return temp; // or return null
}
}


}
 
Back
Top