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. - 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_______________________
-
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;
-
}
-
-
}
-
}
:)
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
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
Hi ,
Thank Frinny. I write back but Does it make sense? - 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(); }
-
-
}
:)
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
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?
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: -
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...really, you should probably try running your application to discover if it even works before posting.
-Frinny
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 - namespace Employeer
-
{
-
public class employee
-
{
-
string name;int salary;public static int count=0;
-
public employee()
-
{
-
name = "Gretchen";
-
salary = 5000;
-
count++;
-
}
-
}
-
-
}
-
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();
-
}
-
}
-
}
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.
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.
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
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... - 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... - 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.
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
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!
I went with this: -
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()
-
{
-
}
-
}
-
Sign in to post your reply or Sign up for a free account.
Similar topics
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,...
|
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...
|
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....
|
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...
|
by: C# |
last post by:
hi
what class can seize http request in .NET framework or c#?
thinks!!
|
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...
|
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...
|
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...
|
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.
|
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?
|
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
|
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...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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...
|
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,...
|
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,...
|
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...
|
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...
|
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,...
| |