Re: Types of constructors
- From: Joshua Flanagan <josh@xxxxxxxxxx>
- Date: Sun, 22 May 2005 15:50:24 -0500
I private constructor is a constructor that is only available to the same class. They can be useful in factory scenarios, where a class creates other instances of its own class and you don't want other classes to be able to instantiate the class in the same way.
For example:
public class Foo {
string name; // this is the only constructor available to other classes
// other classes cannot set the name field directly
public Foo(){
this.name = "DefaultName";
} // this constructor is not available to other classes
// it allows the name field to be set
private Foo(string name){
this.name = name;
} // other classes can call this factory method
public Foo CreateFoo(string fooName){
// calls the private constructor
// and returns a new Foo with the name "fooName"
return new Foo(fooName);
} public string Name { get { return this.name; } }
}You can also have static constructors, which can be used to initialize static fields of the class.
static Foo() { // initialize static fields }
Joshua Flanagan http://flimflan.com/blog
Sathyaish wrote:
What is a private constructor, and why would a class have one? What are the other kinds of constructors besides:
(1) public constructors; and (2) parameterized constructors
And I understand that they are not mutually exclusive of one another. The above classification assimilates my knowledge of having used constructors in both the above manners.
.
- Follow-Ups:
- Re: Types of constructors
- From: Sathyaish
- Re: Types of constructors
- References:
- Types of constructors
- From: Sathyaish
- Types of constructors
- Prev by Date: Types of constructors
- Next by Date: Re: Types of constructors
- Previous by thread: Types of constructors
- Next by thread: Re: Types of constructors
- Index(es):
Relevant Pages
|