Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Preventng direct creation of sub-class instances
Message
From
28/07/2006 11:14:29
Cetin Basoz
Engineerica Inc.
Izmir, Turkey
 
 
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Miscellaneous
Thread ID:
01141060
Message ID:
01141137
Views:
17
>>>>>I tried using:
>>>>>
>>>>>  public class BaseObject
>>>>>    {
>>>>>        private BaseObject() { }
>>>>>    }
>>>>>
>>>>>to prevent other developers directly creating an instance of the class. I was hoping to sub-class from this and have the behaviour inherited by these classes. Seems that's not possible - in fact I can't sub-class from BaseObject at all because 'BaseObject is inaccessible due to it's protection level'. Any other way to achieve what I need (I don't like the idea of having to put private constructors in all the leaf classes)
>>>>>
>
>>>>Wouldn't 'protected' in base do what you want?
>>>
>>>Do you mean 'protected BaseObject(){}'?
>>>That doesn't prevent creation of the object.... :-{
>
>
>>Yes but even private/internal ones could be created anyway. Protected/private/internal at least puts some control over it.
>
>AFAICS, private constructors do (and should) prevent the object from being created. Example:
>
>namespace Test
>{
>    public class MyObject
>    {
>        private MyObject() { }
>
>        public static MyObject NewMyObject()
>        {
>            return new MyObject();
>        }
>    }
>    class Tester
>    {
>        static void Main(string[] args)
>        {
>            // Next line won't compile because of accessibility:
>            //MyObject t = new MyObject();
>            //But you can do it this way:
>            MyObject t = MyObject.NewMyObject();
>        }
>    }
>}
>
>Or am I missing something,
>Viv

Viv,
If that level of protection is OK then 'protected' works.
PS: I thought you'd propagate creation of object to a static ObjectFactory class which creates and returns. Something like:
using System;
using System.Reflection;

namespace myNS
{
 public class myBase
 {
   private string name = "myBase";
   protected myBase() {}
   public string Name {get{return this.name;} set{this.name = value;}}
 }

 public class myBase2: myBase
 {
  private myBase2() { this.Name = "child";}
 }

  public static class ObjectFactory
  {
    public static T Create<T>()
    {
      return (T)Activator.CreateInstance(typeof(T),true);
    }
   }
}
Cetin
Çetin Basöz

The way to Go
Flutter - For mobile, web and desktop.
World's most advanced open source relational database.
.Net for foxheads - Blog (main)
FoxSharp - Blog (mirror)
Welcome to FoxyClasses

LinqPad - C#,VB,F#,SQL,eSQL ... scratchpad
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform