C# class that can't be instantiated more than 10 times

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Angle
    New Member
    • Oct 2010
    • 8

    C# class that can't be instantiated more than 10 times

    Hi,

    I have static variable in my class.
    I use get and set properties.
    I do like below.

    Does it make sense for this question?

    My problem is object call in main(). Please help me out.
    Code:
    namespace Employeer
    {
      public class employee
      {  		
        string name;       
        int salary; 
        public static int count=0;	
        public int stopcount=0;
           
        public string Name()
        { get{	return name;	}
          set{
            if( count>10)
            { name="can’t be instantiated more than 10 times";	
              count=0;
              stopcount=1;
              break;
            }
            else
            {  name=value; }
          }
        }
    }//______________end namespace_______________________
    Code:
    using Employeer;
    
    public class company
    {
      public static void main()
      {
       employee e= new employee();
       Console.WriteLine("Employee name:{0},Salary:{1}",e.Name,e.Salary);
       Console.ReadLine();
    	
       if(e.stopcount!=1)
       {
         e.Name="Susan";
         e.Salary=4000;	     
    			
         Console.WriteLine("Employee name:{0},Salary:{1}",e.Name,e.Salary);
         Console.ReadLine();
       }
       else
       {
         Console.WriteLine("can’t be instantiated more than 10 times");
         break;
       }
    
      }
    }
    Last edited by Frinavale; Oct 4 '10, 08:11 PM. Reason: Please post code in [code] ... [/code] tags. Fixed formatting and some syntax issues.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Angle,

    Welcome to Bytes.
    It sounds like you're fairly new to C# and I was wonder if you understood the concept of a Constructor?

    A Constructor (in C#) is a method that has the same name as the class, and no return type because it is used to "instantiat e" the class. It is called when the an instance of the class is being created. It is the constructor's job to ensure that all of the class members (class variables) are instantiated (using the "new" keyword) so that they can be used.

    If your requirement is to create a class that can only be instantiated 10 times then you need to put the logic to fulfill this requirement in the constructor since the constructor is called when an instance of the class is created (instantiated).


    Right now you have the logic in the "Name" property... But it doesn't belong there.

    Create a constructor and move the logic out of the Name property into the constructor.

    I also recommend that you throw an Exception when someone attempts to instantiate more than 10 classes.

    -Frinny

    Comment

    • Angle
      New Member
      • Oct 2010
      • 8

      #3
      Hi ,
      Thank Frinny. I write back but Does it make sense?
      Code:
      namespace Employeer
      {
            public class employee
            {      		string name;               int salary;		public static int count=0;
      		           
      	     public employee()
      		{   try
      			{              name="Gretchen";
      				salary=5000;
      				count++;
      				if(count>10)
      				{
      				throw new Exception(""can't be instantiated more than 10 times");				               }				
      				
      			}catch(Exception e)
      			{	System.Console.WriteLine(e.ToString());	}
      		}		
      
      }
      using Employeer
      public class company
      {	public static void main()
      	{             employee e= new employee();              }	
      
      }
      Last edited by Niheel; Oct 4 '10, 08:43 PM.

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        :)

        Well it makes more sense than the last Employee class you posted. I wouldn't put a try/catch in your constructor though.

        Let the Exception get thrown to the parent/calling code so that it can catch the Exception. The Exception is thrown because there was a problem (10 instances already exist and you can't create any more)...so it is up to the parent/calling code to deal with the problem.

        -Frinny

        Comment

        • GaryTexmo
          Recognized Expert Top Contributor
          • Jul 2009
          • 1501

          #5
          You look like you're on the right track to me :)

          (Note: Check your allocation math... count defaults to 0)

          When I worked through this when posting back to your other thread (that was deleted) something occurred to me that you should probably think about. How does your program behave when you allocate 10 instances, then say, 5 of them get released?

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            A better test would be to loop through and try and create as many instances of the class as you can...when you encounter a problem (when the exception is thrown) stop looping:
            Code:
            using Employeer
             
            public class company
            {
                public static void main()
                {  
                  boolean errorEncountered = false;
                  while (errorEncountered == false) 
                  {
                    try{
                     employee e= new employee();   
                    }//end of try
                    catch(Exception ex){
                      errorEncountered = true;
                      System.Console.WriteLine(ex.message);
                    }//end of catch  
                   }//end of while
                }//end of the main() method
            }//close namespace
            The above posted testing code will only work properly if you do not catch the exception that you throw in your constructor ;)

            Catching an Exception right after throwing it doesn't really accomplish anything!


            I see a number of syntax errors in the code you've posted. You should correct them before posting your question...real ly, you should probably try running your application to discover if it even works before posting.

            -Frinny
            Last edited by Frinavale; Oct 4 '10, 08:50 PM.

            Comment

            • Angle
              New Member
              • Oct 2010
              • 8

              #7
              Hi, I am very thankful to you and your Forum. This is my right answer. It has run in VS 2008. I hope that no more syntax error in my code. Thanks for helping me
              Code:
              namespace Employeer
              {
                    public class employee
                    {
                    		string name;int salary;public static int count=0;
                          public employee()
                          {
                              name = "Gretchen";
                              salary = 5000;
                              count++;
                          }
              	}	
              
              }
              Code:
               static void Main(string[] args)
                      {
                          bool count = false;
                          while (count == false)
                          {
                              try
                              {
                                  employee e = new employee();
                                  if (employee.count > 10)
                                  {
                                      throw new Exception();
                                  }
              
                              }
                              catch (Exception ex)
                              { count = true;System.Console.WriteLine(ex.ToString());
                                System.Console.WriteLine("can't be instantiated more than 10 times");
                                Console.ReadKey();
                              }
                          }
                      }
              Last edited by Frinavale; Oct 6 '10, 01:56 PM. Reason: In the future, please post code in [code] ... [/code] tags. Added code tags

              Comment

              • Angle
                New Member
                • Oct 2010
                • 8

                #8
                I am sorry Gary. I am not mean to delete it. I was posted same questions. Thanks for remind and helping me. I hope that I got a right answers.

                Comment

                • GaryTexmo
                  Recognized Expert Top Contributor
                  • Jul 2009
                  • 1501

                  #9
                  No no, it's fine. You didn't delete anything, it just got picked up by a mod as a badly formatted question. This thread is much better :)

                  Frinny's answer is great, I just wanted to point out that you're not quite done as objects can be deallocated. I was hoping you'd consider the case where you allocated say, 7 objects, then deallocated 5 of then, then allocated 4 more.

                  Comment

                  • Angle
                    New Member
                    • Oct 2010
                    • 8

                    #10
                    Hi Gary,
                    I am confusing about ( I was hoping you'd consider the case where you allocated say, 7 objects, then deallocated 5 of then, then allocated 4 more.)

                    Would you tell me more? Thanks

                    Comment

                    • GaryTexmo
                      Recognized Expert Top Contributor
                      • Jul 2009
                      • 1501

                      #11
                      It's a little harder to demonstrate in C# apparently where you have less obvious control over when an object is destroyed. Are you familiar with the using statement? This lets you specify the life of an object...

                      Code:
                      using (MyObject o = new MyObject())
                      {
                        // code using o here
                      }
                      // At this point, o is no longer allocated, it is completely destroyed
                      To use this, your object must be disposable; that is, it must inherit from IDisposable and implement the Dispose method.

                      Whew, that's a lot of preamble... thanks for bearing with me! Anyway, consider the following and lets say there was a max instantiation count of 3...

                      Code:
                      MyObject obj1 = new MyObject(); // count is 1
                      MyObject obj2 = new MyObject(); // count is 2
                      using (MyObject obj3 = new MyObject())
                      {
                        // count is 3
                      }
                      // At this point, count should be 2 since obj3 is gone
                      
                      MyObject obj4 = new MyObject(); // count is 3
                      Try this with your code, what is the result? From what you have so far, I'm betting you'll see an exception when instantiating obj4 when in fact, you should not.

                      Comment

                      • Frinavale
                        Recognized Expert Expert
                        • Oct 2006
                        • 9749

                        #12
                        Gary, the other day I was driving home thinking about this question and I was wondering....

                        Is it possible to prevent an object from being instantiated?

                        I remember trying something similar in the past with VB.NET objects. I tried to set Me=Nothing (in c# this would be the same as this=null;) but I was not allowed to do this.

                        Does throwing an exception in the constructor prevent the object from being created?

                        (Sorry, right now I have no way to test this...which is why I'm asking)

                        -Frinny

                        Comment

                        • GaryTexmo
                          Recognized Expert Top Contributor
                          • Jul 2009
                          • 1501

                          #13
                          It looks like throwing an exception does indeed prevent the instantiation. I wrote up a test program, check your PMs, I'll send it to you.

                          For the record, I freaking love C# Express Edition (2008 and up) for sandboxing. That throwaway project feature is absolutely wonderful!

                          Comment

                          • Plater
                            Recognized Expert Expert
                            • Apr 2007
                            • 7872

                            #14
                            I went with this:
                            [code=c#]
                            public class myClass
                            {
                            private static int count = 0;
                            public static myClass CreateInstance( )
                            {
                            if (count < 10)
                            {
                            count++;
                            return new myClass();
                            }
                            else
                            {
                            return null;//or throw an exception?
                            }
                            }
                            private myClass()
                            {
                            }
                            }
                            [/code]

                            Comment

                            Working...