0

I am developing an application in C# with winforms. I am pretty good with C++ but very new to C# so please forgive my ignorance.

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

         class obj
        {
            private int member;
            public obj(int n)
            { member = n; }

        }

        obj[] obj_arr = new obj[10];
        obj_arr[0] = new obj(4); // Problem Here
    }

}

This is a very simplified example of what I am trying to do, but as you can see I would like to declare an array of user defined objects. The problem I am having is that when I try to initialize the individual array member the compiler gives me an error. Actually it gives several errors. obj_arr[0] is highlighted with an error saying that it is a field but is being used as a type. The = is also highlighted with an error that says = is invalid token in class, struct, or interface declaration. Finally obj(4) is highlighted with an error saying method must have a return type.

I am a little stumped here, any help would be greatly appreciated.

New Code

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();

         obj_arr[0] = new obj(4); // Problem Here

    }

    class obj
    {
        private int member;
        public obj(int n)
        { member = n; }

    }

    obj[] obj_arr = new obj[10];
    obj o1 = obj_arr[0];

}
0

1 Answer 1

5

You're trying to execute code within the class definition. Only member initialization con occur outside of methods. Move that code to to another method, or the constructor:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();

        obj_arr[0] = new obj(4); // Problem Here

        o1 = obj_arr[0];
    }

    class obj
    {
        private int member;
        public obj(int n)
        { member = n; }

    }

    obj[] obj_arr = new obj[10];

    obj o1;
}

That should make all of the compiler errors go away (one syntax error is causing another).

Sign up to request clarification or add additional context in comments.

3 Comments

Yes I agree but it was just a quick example, I would never use obj as the name of a class in real code.
Ok I think I understand whats going on a little bit better now. However I need to be able to do something like this... Edit: Wasn't able to post formatted code in this comment so I added it to the end of my original question.
That needs to be done in a method as well - I'll edit my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.