473,785 Members | 2,380 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to allow instanciation of a class from another class method inside the same assembly???

Hello,

I'd like to be able to allow instanciation of a class (class Class_A) only
from another class method (class Class_B). And I'd like to write the
necessary code to enforce this behavior even inside the same assembly where
class Class_A and Class_B are defined.
I've written the code that does this BUT I'd like to understand if this is
the most correct way to obtain such a result.

This is my simplified code:

// abstract class
public abstract class Class_C
{
public abstract void Method_1();
}

public class Class_B
{
// method that returns instances of class Class_A
public Class_A Method_2()
{
return new Class_A();
}

// nested private class - implements the abstract class Class_C
private class Class_A : Class_C
{
public override void Method_1
{
// implementation code
}
}
}

The above implentation allows the writing of the following "client" code:

Class_B b = new Class_B();
Class_C c = b.Method_2(); // creating an instance of class Class_A
c.Method_1(); // calling Method_1() of class Class_A

This code works well, the only thing I don't like is that Class_A is
completely unknown by code outside class Class_B.
Instead of an abstract class I could have used an interface but, since I
won't need to implement that interface more than once, I thought using an
abstract class to hold a reference to an instance of class Class_A to be
more correct.

Can anyone review this approach and tell me if there is any better solution?
Bob Rock


Jul 21 '05 #1
11 1698
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]
Jul 21 '05 #2
> 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

Jul 21 '05 #3
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 ConsoleApplicat ion1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class ClassC
{
public void SayHello()
{
Console.WriteLi ne("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" <no************ *************** @hotmail.com> wrote in message
news:uz******** ******@TK2MSFTN GP09.phx.gbl...
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

Jul 21 '05 #4
Bob, another avenue that you could take for this kind of behaviour is to
only allow the instanciation of ClassC if and only if an instance of ClassA
is passed to it. You could then do validaty checking on the ClassA object if
necessary.

e.g.
using System;

namespace ConsoleApplicat ion1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class ClassC
{
public void SayHello()
{
Console.WriteLi ne("Hello");
}

public ClassC(ClassB key)
{
//constructor must have instance of ClassB passed to it otherwise compile
time error will occur
//in order to return error at run time instead you could Add back a
public ClassC() constructor
//and throw an exception in it.
}
}

public class ClassB
{
//any implementation you require
}

public class AppStart
{
[STAThread]
static void Main(string[] args)
{
//ClassC c = new ClassC(); //would fail
//c.SayHello();

ClassC c = new ClassC(new ClassB());
c.SayHello();

Console.ReadLin e();
}
}
}

--

--

Br,
Mark Broadbent
mcdba , mcse+i
=============
"Bob Rock" <no************ *************** @hotmail.com> wrote in message
news:uz******** ******@TK2MSFTN GP09.phx.gbl...
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

Jul 21 '05 #5
> 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


This point is not exactly clear to me.

Bob Rock
Jul 21 '05 #6
Mark, thank you for your effort.
Anyhow I identifies another possible solution that removes the "problem" of
the abstract class.
// -- the managed class
public class ManagedClass
{
// -- non public constructor
protected ManagedClass()
{

}
}

// -- the manager class
public class ManagerClass
{
// -- method returning an instance of managed class
public ManagedClass CreateInstance( )
{
return new PrivateManagedC lass();
}

// -- nested class
private PrivateManagedC lass : ManagedClass
{
public PrivateManagedC lass() : base()
{

}
}
}

Why not have ManagerClass directly inherit from ManagedClass? Because I
don't want to expose ManagedClass methods on ManagerClass.
Bob Rock


Jul 21 '05 #7
Ill try to explain better.

Imagine that we got ClassC and we have found a way to stop it being
constructed outside of ClassC *except* we need to find a way to allow ClassB
to instanciate it. My thoughts were that we could create a public (non
static) method (within ClassC) that returns an object instance of type C.
Obviously the method is non static and so it can only be called through an
instance of ClassC (which we have just said cannot be done on its own)
HOWEVER I thought why not inherit ClassC into ClassB allowing us to call
the method (and return a type instance) through base.MethodName ().
Unfortunately since the ClassC constructor is private, that in itself
prevents the class being inherited, and therefore the pack of cards comes
falling down again.

Hope I made more sense that time?

--

--

Br,
Mark Broadbent
mcdba , mcse+i
=============
"Bob Rock" <no************ *************** @hotmail.com> wrote in message
news:%2******** *******@TK2MSFT NGP11.phx.gbl.. .
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


This point is not exactly clear to me.

Bob Rock

Jul 21 '05 #8
> Imagine that we got ClassC and we have found a way to stop it being
constructed outside of ClassC *except* we need to find a way to allow ClassB to instanciate it. My thoughts were that we could create a public (non
static) method (within ClassC) that returns an object instance of type C.
Obviously the method is non static and so it can only be called through an
instance of ClassC (which we have just said cannot be done on its own)
HOWEVER I thought why not inherit ClassC into ClassB allowing us to call
the method (and return a type instance) through base.MethodName ().
Unfortunately since the ClassC constructor is private, that in itself
prevents the class being inherited, and therefore the pack of cards comes
falling down again.


Clear. A protected constructor would do the job.

Bob Rock
Jul 21 '05 #9
yes well done! a protected constructor gets around this issue. The only
potential problem I can see with all this, is that if the ManagedClass has
public members, then they will be accessible through the ManagerClass
instance (because they will be inherited).
Anyway you seem to have got where you wanted so I'll sign off for now.

bye.

--

--

Br,
Mark Broadbent
mcdba , mcse+i
=============
"Bob Rock" <no************ *************** @hotmail.com> wrote in message
news:et******** ******@TK2MSFTN GP09.phx.gbl...
Mark, thank you for your effort.
Anyhow I identifies another possible solution that removes the "problem" of the abstract class.
// -- the managed class
public class ManagedClass
{
// -- non public constructor
protected ManagedClass()
{

}
}

// -- the manager class
public class ManagerClass
{
// -- method returning an instance of managed class
public ManagedClass CreateInstance( )
{
return new PrivateManagedC lass();
}

// -- nested class
private PrivateManagedC lass : ManagedClass
{
public PrivateManagedC lass() : base()
{

}
}
}

Why not have ManagerClass directly inherit from ManagedClass? Because I
don't want to expose ManagedClass methods on ManagerClass.
Bob Rock

Jul 21 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
1142
by: Bob Rock | last post by:
Hello, I'd like to be able to allow instanciation of a class (class Class_A) only from another class method (class Class_B). And I'd like to write the necessary code to enforce this behavior even inside the same assembly where class Class_A and Class_B are defined. I've written the code that does this BUT I'd like to understand if this is the most correct way to obtain such a result. This is my simplified code:
2
2056
by: Bob Rock | last post by:
Hello, in the last few days I've made my first few attempts at creating mixed C++ managed-unmanaged assemblies and looking afterwards with ILDASM at what is visible in those assemblies from a managed point-of-view I've noticed that: 1) for each managed and unmanaged C function (not C++ classes) I get a public managed static method (defined on a 'Global Functions' class) in the generated assembly with an export name of the form
19
1981
by: hamil | last post by:
I have a form with one button, Button1, and a Textbox, Textbox1 I have a class, class1 as follows. Public Class Class1 Public DeForm As Object Sub doit() DeForm.Textbox1.text = "It works" End Sub End Class
2
1686
by: tony | last post by:
Hello! I'm trying to build a class library which has a class called AvestaPlantFunc. In this project building a class libray exist a class called AvestaPlantFunc. In this class is there a method called IsBottomMixValid. Code not relevant for the question has been removed. This method IsBottomMixValid has one parameter and the type for this parameter is MeltPracDataGmix meaning passing class reference MeltPracDataGmix.
5
2123
by: ffrugone | last post by:
My scenario involves two classes and a database. I have the classes "Broom" and "Closet". I want to use a static method from the "Closet" class to search the database for a matching "Broom". If it finds a matching "Broom", i want it to return a "Broom" object to the calling program. I want the static method to call the constructor for the "Broom" class. I want this static method, (and one other called "CreateBroom") to be the only...
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10315
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9947
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7494
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5379
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4045
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.