Reputation: 3415
In the following italicized code, why don't we put "IntIndexer" in front of myData = new string[size]; since Customer cust = new Customer(); (assuming Customer is the name of the class):
*Customer cust = new Customer();*
using System;
/// <summary>
/// A simple indexer example.
/// </summary>
class IntIndexer
{
private string[] myData;
public IntIndexer(int size)
{
*myData = new string[size];*
for (int i = 0; i < size; i++)
{
myData[i] = "empty";
}
}
Upvotes: 1
Views: 331
Reputation: 116664
To break this down:
Customer cust = new Customer();
This can be broken into two parts:
Customer cust;
cust = new Customer();
The first line says that the name cust
will be able to refer to objects of type Customer
. The second line creates a new Customer
object and makes cust
refer to it.
The other example you give is already broken into those two parts:
private string[] myData;
and:
myData = new string[size];
If the array of strings was to be of a constant length, we could collapse this onto one line as well, in IntIndexer
(before the constructor).
private string[] myData = new string[100];
But we need to use the size
passed into the IntIndexer
constructor, so we have to split the declaration and initialization into two steps.
Upvotes: 5
Reputation: 5417
myData is already declared as a field of IntIndexer class, so you don't have to redeclare it in the constructor. The class understands that it is referencing its own field.
Upvotes: 0
Reputation: 116977
They're two different things. myData has been declared as type string[]
, not of type IntIndexer
.
The class IntIndexer
contains a variable called myData
. They are not equivalent.
You also wouldn't put the type in front of that line of code anyway, because you'd be redeclaring the variable. Doing so would give you a compiler error.
Upvotes: 0
Reputation: 1062640
The first line (cust
) is declaring and initialising a field or variable.
In the second example, the field (myData
) is declared against the type, and intialised in the constructor (IntIndexer(...)
). If (in the constructor) we placed a type before it, we would be declaring a local variable with the same name. This would be confusing (you'd then have to use this.myData
and myData
to refer to the field and variable respectively).
Upvotes: 5
Reputation: 11910
Are you trying to put a call to a constructor within itself? As in if you want to instantiate IntIndexer you have to call this function and repeat the process until either you realize this will cause a stack overflow or just never terminate as it will always be trying to create the nth instance as n just keeps going and going up.
What am I missing in your example if I simply trace it that way?
Upvotes: 0