Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Create Instance Of Class Through Method Call Only?
Message
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Miscellaneous
Thread ID:
01464302
Message ID:
01464386
Views:
36
>>>Then this defeats the whole purpose. I don't want the class to be created from outside my factory. I want to be able to set things
>>>on the instance before returning it to the caller.
>>
>>Then I think your options are limited. Either
>>(a) Create a CTOR for the class with parameters that accept the values you want to set
>>or
>>(b) Make the class private and hide it behind an interface.
>
>If you think of something like a DataReader. You cannot directly instantiate this class. You need a Command class to return a data
>reader. How is this done? Somehow they're only allowing the class to be created via the Command. There must be a way.

Maybe something like:
namespace Whatever
{
    public class MySQLDataReader
    {
        internal MySQLDataReader() { }
    }

    public class MySQLCommand
    {
        public MySQLDataReader ExecuteReader()
        {
            MySQLDataReader msdr = new MySQLDataReader();
            //Do whatever....
            return new MySQLDataReader();
        }
    }
}
Then from another assembly:
Whatever.MySQLCommand msc = new Whatever.MySQLCommand();
Whatever.MySQLDataReader dr = msc.ExecuteReader();
 Whatever.MySQLDataReader dr2 = new Whatever.MySQLDataReader();  //Compile error: The type has no constructors defined
>Could you elaborate on what you mean by " hide it behind an interface."?
Again in a separate assembly:
public interface ICustomer
    {
        string Name { get; set; }
    }

    class Customer: ICustomer
    {
        public string Name { get; set; }
    }

    public static class CustomerCreator
    {
        public static ICustomer CreateCustomer()
        {
            Customer c = new Customer() { Name = "Fred" };
            return c;
        }
    }
Then to create:
Whatever.ICustomer cust = Whatever.CustomerCreator.CreateCustomer();
First one probably best for your requirements tho....
Previous
Reply
Map
View

Click here to load this message in the networking platform