Following one is a simple program. I inserted static key word to the object class variable idNumber. Program is compiling fine, but I expected an error message. Please explain me what is the reason for its compilation with or without key word static.
using System;
public class CreateEmployee
{
public static void Main()
{
Employee myAssistant = new Employee();
myAssistant.SetId(345); //Instance Method
Console.WriteLine("ID # is {0}", myAssistant.GetId());
Console.ReadKey();
}
}
internal class Employee
{
private static int idNumber;
public int GetId()
{
return idNumber;
}
public void SetId(int id)
{
idNumber = id;
}
}
//ID # is 345
Loading
VulpesPosted Jun 25, 2013, 7:02 AM
This is why there's only one copy for the class as a whole and why it knows nothing about any particular instances.
If idNumber were an instance field, then it would be stored within the memory set aside on the heap for each instance and consequently each instance would have its own copy.
So in your program the two instances, mAssistant1 and myAssistant2, are accessing the same memory location and this therefore returns the same value when GetId() is called successively on each instance.
Posted Jun 25, 2013, 7:09 AM
Posted Jun 25, 2013, 6:50 AM
using System;
public class CreateEmployee
{
public static void Main()
{
Employee myAssistant1 = new Employee();
myAssistant1.SetId(345);
Employee myAssistant2 = new Employee();
myAssistant2.SetId(346);
Console.WriteLine("ID # is {0}", myAssistant1.GetId());
Console.WriteLine("ID # is {0}", myAssistant2.GetId());
Console.ReadKey();
}
}
internal class Employee
{
private static int idNumber;
public int GetId()
{
return idNumber;
}
public void SetId(int id)
{
idNumber = id;
}
}
/*
D # is 346
D # is 346
*/
Posted Jun 25, 2013, 5:20 AM
VulpesPosted Jun 25, 2013, 3:26 AM
However, the program no longer makes much sense.
If you create another Employee object and call SetId with a value (say) of 346 and now call GetId on the original object, you'll find that this now returns 346 as well!
This is because there's now only one idNumber field for the entire class, not one per instance as there should be.
Jignesh TrivediPosted Jun 24, 2013, 11:04 PM
hi,
why you expecting error here?
in this code you are calling GetId method which is public and accessable with in module or assambaly level.
if you are accessing private member directly than it gave error....
as per my knowledge, all member of class are initialize when you create object of the class.
hope this will help you.