As Morton has shown you, you can prevent a class from being instanciated
from outside its type by making it's constructer private to its' class. That
is essentially what you want. Remember that your class C needs to be public
in order to assign that type to the reference pointer. I know you want one
class to be the ONLY ONE to be able to return objects of another type but
from what I see there are 2 problems to this.
1. To force a type to be inherited you would make it abstract, but by making
it abstract you cannot instanciate objects of its type (which you need to
do)
2. By hiding the constructor from outside the type you are preventing the
class from being inherited, which prevents you from returning an object of
its type from outside its class using the base object
Morton way to have a type become it's own object factory is the best way to
do what you what (as far as I can figure out). Please see code.
using System;
namespace ConsoleApplication1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class ClassC
{
public void SayHello()
{
Console.WriteLine("Hello");
}
private ClassC()
{
//constructor is only visible within its own type
}
public static ClassC ReturnC()
{
return new ClassC();
}
}
public class AppStart
{
[STAThread]
static void Main(string[] args)
{
//ClassC c = new ClassC(); //would fail
//c.SayHello();
ClassC c = ClassC.ReturnC();
c.SayHello();
}
}
}
--
Br,
Mark Broadbent
mcdba , mcse+i
=============
"Bob Rock" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> > Hi Bob,
> >
> > Well, your code does not compile :P (or at least did not for me).
> Something about the return type being less accessible than the method.
> However, changing the return type for Method_1 to Class_C will do the
trick,
> but I suspect you did so already.
> >
> > There is another approach of controlled instantiation which only
involves
> one class.
> >
> > public class Class_A
> > {
> > private Class_A()
> > {
> > }
> >
> > public void Method_1()
> > {
> > }
> >
> > public static Class_A Method_2()
> > {
> > return new Class_A();
> > }
> >
> > }
> >
> >
> > Happy coding!
> > Morten Wennevik [C# MVP]
>
>
> Morten,
>
> I'm sorry, I had to clean up my code to make the post and made a mistake.
> Method_1 indeed returns an instance of Class_C.
>
> Morten thank you for your code but it is not what I was asking for.
> I'd like a class method (class Class_B method) to be the only one able to
> return instances of a ANOTHER class (class Class_A).
>
>
> Bob Rock
>
>
>
|