简体   繁体   中英

What's the difference between these two lines? (C#)

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";
        }
    }

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).

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.

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM