473,396 Members | 1,797 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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

8
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.
Expand|Select|Wrap|Line Numbers
  1. namespace Employeer
  2. {
  3.   public class employee
  4.   {          
  5.     string name;       
  6.     int salary; 
  7.     public static int count=0;    
  8.     public int stopcount=0;
  9.  
  10.     public string Name()
  11.     { get{    return name;    }
  12.       set{
  13.         if( count>10)
  14.         { name="can’t be instantiated more than 10 times";    
  15.           count=0;
  16.           stopcount=1;
  17.           break;
  18.         }
  19.         else
  20.         {  name=value; }
  21.       }
  22.     }
  23. }//______________end namespace_______________________
Expand|Select|Wrap|Line Numbers
  1. using Employeer;
  2.  
  3. public class company
  4. {
  5.   public static void main()
  6.   {
  7.    employee e= new employee();
  8.    Console.WriteLine("Employee name:{0},Salary:{1}",e.Name,e.Salary);
  9.    Console.ReadLine();
  10.  
  11.    if(e.stopcount!=1)
  12.    {
  13.      e.Name="Susan";
  14.      e.Salary=4000;         
  15.  
  16.      Console.WriteLine("Employee name:{0},Salary:{1}",e.Name,e.Salary);
  17.      Console.ReadLine();
  18.    }
  19.    else
  20.    {
  21.      Console.WriteLine("can’t be instantiated more than 10 times");
  22.      break;
  23.    }
  24.  
  25.   }
  26. }
Oct 4 '10 #1

✓ answered by Frinavale

:)

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

13 3293
Frinavale
9,735 Expert Mod 8TB
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 "instantiate" 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
Oct 4 '10 #2
Angle
8
Hi ,
Thank Frinny. I write back but Does it make sense?
Expand|Select|Wrap|Line Numbers
  1. namespace Employeer
  2. {
  3.       public class employee
  4.       {              string name;               int salary;        public static int count=0;
  5.  
  6.          public employee()
  7.         {   try
  8.             {              name="Gretchen";
  9.                 salary=5000;
  10.                 count++;
  11.                 if(count>10)
  12.                 {
  13.                 throw new Exception(""can't be instantiated more than 10 times");                               }                
  14.  
  15.             }catch(Exception e)
  16.             {    System.Console.WriteLine(e.ToString());    }
  17.         }        
  18.  
  19. }
  20. using Employeer
  21. public class company
  22. {    public static void main()
  23.     {             employee e= new employee();              }    
  24.  
  25. }
Oct 4 '10 #3
Frinavale
9,735 Expert Mod 8TB
:)

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
Oct 4 '10 #4
GaryTexmo
1,501 Expert 1GB
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?
Oct 4 '10 #5
Frinavale
9,735 Expert Mod 8TB
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:
Expand|Select|Wrap|Line Numbers
  1. using Employeer
  2.  
  3. public class company
  4. {
  5.     public static void main()
  6.     {  
  7.       boolean errorEncountered = false;
  8.       while (errorEncountered == false) 
  9.       {
  10.         try{
  11.          employee e= new employee();   
  12.         }//end of try
  13.         catch(Exception ex){
  14.           errorEncountered = true;
  15.           System.Console.WriteLine(ex.message);
  16.         }//end of catch  
  17.        }//end of while
  18.     }//end of the main() method
  19. }//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...really, you should probably try running your application to discover if it even works before posting.

-Frinny
Oct 4 '10 #6
Angle
8
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
Expand|Select|Wrap|Line Numbers
  1. namespace Employeer
  2. {
  3.       public class employee
  4.       {
  5.               string name;int salary;public static int count=0;
  6.             public employee()
  7.             {
  8.                 name = "Gretchen";
  9.                 salary = 5000;
  10.                 count++;
  11.             }
  12.     }    
  13.  
  14. }
Expand|Select|Wrap|Line Numbers
  1.  static void Main(string[] args)
  2.         {
  3.             bool count = false;
  4.             while (count == false)
  5.             {
  6.                 try
  7.                 {
  8.                     employee e = new employee();
  9.                     if (employee.count > 10)
  10.                     {
  11.                         throw new Exception();
  12.                     }
  13.  
  14.                 }
  15.                 catch (Exception ex)
  16.                 { count = true;System.Console.WriteLine(ex.ToString());
  17.                   System.Console.WriteLine("can't be instantiated more than 10 times");
  18.                   Console.ReadKey();
  19.                 }
  20.             }
  21.         }
Oct 4 '10 #7
Angle
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.
Oct 4 '10 #8
GaryTexmo
1,501 Expert 1GB
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.
Oct 4 '10 #9
Angle
8
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
Oct 4 '10 #10
GaryTexmo
1,501 Expert 1GB
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...

Expand|Select|Wrap|Line Numbers
  1. using (MyObject o = new MyObject())
  2. {
  3.   // code using o here
  4. }
  5. // 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...

Expand|Select|Wrap|Line Numbers
  1. MyObject obj1 = new MyObject(); // count is 1
  2. MyObject obj2 = new MyObject(); // count is 2
  3. using (MyObject obj3 = new MyObject())
  4. {
  5.   // count is 3
  6. }
  7. // At this point, count should be 2 since obj3 is gone
  8.  
  9. 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.
Oct 4 '10 #11
Frinavale
9,735 Expert Mod 8TB
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
Oct 6 '10 #12
GaryTexmo
1,501 Expert 1GB
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!
Oct 6 '10 #13
Plater
7,872 Expert 4TB
I went with this:
Expand|Select|Wrap|Line Numbers
  1. public class myClass
  2. {
  3.   private static int count = 0;
  4.   public static myClass CreateInstance()
  5.   {
  6.         if (count < 10)
  7.         {
  8.             count++;
  9.             return new myClass();
  10.         }
  11.         else
  12.         {
  13.             return null;//or throw an exception?
  14.         }
  15.   }
  16.   private myClass()
  17.   {
  18.   }
  19. }
  20.  
Oct 6 '10 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Simon Harvey | last post by:
Hi, Does anyone know an easy way to identify the exceptions that a class can potentially throw. I was looking for a list of the exceptions that the Hashtable class can potentially provide,...
12
by: Bryan Parkoff | last post by:
CMain Class is the base class that is initialized in main function. CA Class is the base class that is initialized in CMain::CMain(). CMain Class is always public while CA Class is always...
8
by: Dev | last post by:
Hello, Why an Abstract Base Class cannot be instantiated ? Does anybody know of the object construction internals ? What is the missing information that prevents the construction ? TIA....
1
by: ad | last post by:
I used the code below to export a table in a dataset to Excel. It can export only on table at a time. Can export more than on table in a dataset to Excel public static void...
4
by: C# | last post by:
hi what class can seize http request in .NET framework or c#? thinks!!
8
by: blisspikle | last post by:
Can any Public class be inherited from? I installed some software on my pc and I can use it in my code, but I cannot seem to inherit from it. It was an executable that installed on my pc, I do not...
2
by: antonyfran | last post by:
hey can some please tell me how to run this class a specific number of times. maybe by using a for loop?. i am making a game called memory game where you match the cards which are the same. i want...
77
by: borophyll | last post by:
As I read it, C99 states that a byte is an: "addressable unit of data storage large enough to hold any member of the basic character set of the execution environment" (3.6) and that a byte...
1
by: fuatsungur | last post by:
Do you know is there any GSM modem that can handle more than 1000 sms per minute and what is it model? Or, do you know nowly modems, how much send sms per minute? Thanks for responses.
3
mickey0
by: mickey0 | last post by:
hello, I read this server class, and I'm wondering how modify it in a way that the server can serve more than one request. link Could anyone get me a hint, please?
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
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,...

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.