I learn C# and try to understand the logic between static and Constructor right now. One thing I need ask you about an example which I will give at below. (please ignore the quality of code or how could be written better things, I just need to understand the logic which I am asking)
There are 2 classes named Computer and BaseType. Computer inherits from BaseType and I am taking instance from Computer class.
In short, I wanted to gave an ID number to "Id" field in BaseType Class increasingly (starting from 1 and then 2,3,4 etc when the Computer class' instance has been taken). As I do that, I realized something interesting and wanted to ask you this logic to you.
Lemme give the sample code.
Main() Class
static void Main(string[] args)
{
Computer C1 = new Computer();
Computer C2 = new Computer();
Computer C3 = new Computer();}
Computer() Class
public class Computer : Product
{
public string Cpu { get; set; }
public string Ram { get; set; }
public string VideoCard { get; set; }
}
BaseType() Class
public class BaseType
{
static int counter = 1;
private int _Id;
public int Id
{
get
{
return _Id;
}
private set
{
}
}
public BaseType()
{
_Id = IdAssignment();
}
int IdAssignment()
{
return counter++;
}
I put breakpoints to each instances as taken them, also to constructor method and IdAssignment() method. ("Computer C1 = new Computer();" and so on)
Question1: As I taking instance as "C1", I realized that counter is "2" cause it's 1 because it's static in the beginning and has counter++. But, in constructor method, "_Id" is getting "1" instead of "2" and it continues so on. Normally it's what I want but I don't know how this happening. This I want to ask first.
Question2: As I am doing it, I realized that "_Id" in contructor method is always "0" before taking the "IdAssignment()"'s value. Shouldn't it be normally "1" as I come to taking second instance (C2)? This I want to ask you secondly.
Thanks
counter
field - because it doesn't belong to any specific instance (but to the class itself). It's like a separate scratch pad where you are saving the last used ID. When you create a new instance, the the_Id
always starts out as 0, then in the constructor, you look up where the counter is currently at, and assign the value based on that.