Peter C
Peter C

Reputation: 3

Strange behaviour/error when splitting one line of code into two lines in class

I have one line of code like the following:

    private ProductList list = ProductList.GetProductList();

where ProductList is a serializable class with the static method GetProducList. If I put it like above everything works fine, but if I split the line into two lines, like the following:

    private ProductList list;
    list = ProductList.GetProductList();

then, if I put my mouse marker over list in the second row, I get the error "C#: Unknown type list". I also get the following errors when putting the mouse marker over GetProductList(); "C#: Unknown type GetProductList of 'MySolution.Library.ProductList'", "C#: Unexpected end of declaration", "C#: There already is another member named ''", and finally "C#: There already is another type named ''".

Any ideas?

Upvotes: 0

Views: 37

Answers (1)

Coding Flow
Coding Flow

Reputation: 21881

You haven't shown the code but I suspect because of the private access modifier you have declared list as a field. The first works because it is valid to declare and initialise a field in that way, however the second doesn't work becuase, well you can't. Something similar to the second 2 lines of code would work fine in a method, but you can't use access modifiers on variables.

Below is valid

public class MyController : Controller
{
    private ProductList list = ProductList.GetProductList();
}

Below is not

public class MyController : Controller
{
    private ProductList list;
    list = ProductList.GetProductList();
}

Below is also valid:

public class MyController : Controller
{
    private void SomeMethod()
    {
        ProductList list;
        list = ProductList.GetProductList();
    }
}

You could also initialise the field in the constructor

public class MyController : Controller
{
    private ProductList list;
    public MyController()
    {
        list = ProductList.GetProductList();
    }       
}

Upvotes: 2

Related Questions