class instantiates itself

  • Thread starter Thread starter bill tie
  • Start date Start date
B

bill tie

class Program
{
...
...

static void Main()
{
Program program = new Program();
}
}

- Is it a good practice to have a class instantiate itself?
- What is the rationale for doing it?
- Is Program a quasi singleton?

Thank you.
 
bill tie said:
class Program
{
...
...

static void Main()
{
Program program = new Program();
}
}

- Is it a good practice to have a class instantiate itself?

It's not bad practice. There are plenty of reasons to do so. The .Net
framework itself does this in cases. For example look at the IClonable
interface.

Andrew Faust
 
bill said:
class Program
{
...
...

static void Main()
{
Program program = new Program();
}
}

- Is it a good practice to have a class instantiate itself?

Yes, if it makes sense for that specific class.
- What is the rationale for doing it?

It's done whenever a method needs to return a new instance of the class.

For example, all the methods in the String class that returns a new
string (Substring, Format, Concat, Replace, ToUpper, ToLower, Insert,
Remove, Trim, et.c.) are creating new instances of the String class.
- Is Program a quasi singleton?

No, it's just a class that it doesn't make sense to create more than one
instance of. If you would eventhough, they would be separate instances.

However, as the program is written to have only one instance of the
class, the person implementing the class might have used short cuts that
depends on this fact, which could cause problems if you would create
more than one instance of it.
 
class Program
{
  ...
  ...

  static void Main()
  {
    Program program = new Program();
  }

}

- Is it a good practice to have a class instantiate itself?

Of course!!! , it's a VERY common used practice in different pattern,
like Singleton.
- What is the rationale for doing it?

There can be a lot of reasons, a couple of reasons:
1- You do not want the class to have a public constructor (take a look
at the Guid class in the framework) so you expose a method that
returns a created instance
2- The class is non modificable (like string) so each method that
implicate a change returns a new instance.
- Is Program a quasi singleton?

Not really, You can even have a singleton that do not follow this.
but yes, they are related in a way as the singleton usually use this
techinique
 

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

Back
Top