public string bob = "hello";

This works

public string bob;
bob = "hello";

This does not?

Thank you

The second doesn't work because you are trying to put code ( bob = "hello"; ) outside of a method (we know it's outside of a method because of the 'public' on bob, you can't declare public method variables).

Both are not in a method? Their root is a class if that makes sense?

Public method variables? I'll try read up on it :) Thank you.

I should work. Take a look at this simple example:

class MyClass
    {
        string a; //this will not be initialized, but there will be no error in compile time
        string b = "b";
        public void MyMethod()
        {
            a = "a";
            string c;  //this will not be initialized, but there will be no error in compile time
            string d = "d";
        }
    }

This all works.

Sorry if I was a bit vague. Here is an example:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private string toType;
        toType = "Hello World!";

        private void btnStart_Click(object sender, EventArgs e)
        {
            MessageBox.Show(toType);
        }

    }

Error: Invalid token '=' in class, struct, or interface member declaration.

Why won't this work?
As from what I can understand from your post Mitja, I can only assign values to a variable within a method? But if I replace

private string toType;
toType = "Hello World!";

with

private string toType = "Hello World!";

It works? Is this a syntax thing?

Edited 5 Years Ago by spunkywacko: n/a

private string toType = "Hello World!";

This is variable initialization. It is a special case where you can have code outside a method. Anything after the '=' sign is executed during class instanciation.

private string toType;
toType = "Hello World!";

This is an attempt to place code outside a method. When is it supposed to execute? Since the compiler can't figure out when you want it to do this, it generates an error.

private string toType = "Hello World!";

This is variable initialization. It is a special case where you can have code outside a method. Anything after the '=' sign is executed during class instanciation.

private string toType;
toType = "Hello World!";

This is an attempt to place code outside a method. When is it supposed to execute? Since the compiler can't figure out when you want it to do this, it generates an error.

Thank you, made complete sence when you said 'Since the compiler can't figure out when you want it to do this'!

This question has already been answered. Start a new discussion instead.