Need some explanation with novice C # code

I started to learn C #. I am trying to declare a class and some variables and try to perform simple string concatenation. But I get some error - the code below

namespace ConsoleApplication1
{
    class Class1
    {
        string s1 = "hi";
        string s2 = "hi";
        string s3 = s1 + s2;
    }
}

The error I get is that the Field Initializer cannot reference non-static fields, method, property 'ConsoleApplication1.Class1.s1

Can someone explain what is happening here.

Thank.

+5
source share
3 answers

Can someone explain what is happening here.

Well, a compiler error message says that, really, when you finish the terminology. This line is not valid:

string s3 = s1 + s2;

, (s1 + s2 ) , - . , :

string s3 = this.s1 + this.s2;

10.5.5.2 # 4:

. , this , .

( , ...)

:

class Class1
{
    string s1 = "hi";
    string s2 = "hi";
    string s3;

    public Class1()
    {
        s3 = s1 + s2;
    }
}
+15

[] . , .

:

class Class1
{
    string s1 = "hi";
    string s2 = "hi";
    string s3;

    public Class1()
    {
         s3 = s1 + s2;
    }
}
+8

Try initializing s3in a method, preferably a constructor

class Class1
{
    string s1 = "hi";
    string s2 = "hi";
    string s3;


    public Class1()
    {
        s3 = s1 + s2;
    }
}
+6
source

All Articles