beginner C# constructor, how to return null ?

  • Thread starter Romain TAILLANDIER
  • 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
 
J

Jon Skeet

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.
 
M

msnews.microsoft.com

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!
**********************************************************************
 
B

Bret Mulvey

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
}
}


}
 

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