C # question for VBer. Should private Static fields be declared?

I am a vb.net programmer switching to C #.

I have the following code for a console application (targeting NET20)

using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


namespace eScoreSwapper
{
    class Program
    {
        private string _dbName = ConfigurationManager.AppSettings["dbName"];

        static void Main(string[] args) {}

        static void InitVars()
        {
            if (string.IsNullOrEmpty(_dbName)) _dbName = "";
        }
    }
}

This gives a compilation error in the if InitVars clause for the _dbName variable:

Error   1   An object reference is required for the non-static field, method, or property 'eScoreSwapper.Program._dbName'   C:\Users\SethS\Documents\eScore\Versions\Trunk\dotNet\eScoreSwapper\eScoreSwapper\Program.cs    26  38  eScoreSwapper

This is because it is true. C # does not allow to refer to private fields of a class if they are not declared static? I'm sure I'm doing something wrong.

While I am, I can ask another C # question. Why does the if statement work? Why aren't braces required? Is this a valid syntax if the condition is followed by a single expression (as in t-sql IF).

Thank you for your help.

Set

+3
source share
7 answers

, , , . , static InitVars().

, :

static void Main(string[] args) 
{
   InitVars();
} 

, static InitVars(). . , , Main() .

static void Main(string[] args) 
{
   Program prog = new Program();
   prog.InitVars();
} 

If()

if (string.IsNullOrEmpty(_dbName)) _dbName = "";

- :

if (string.IsNullOrEmpty(_dbName)) 
     _dbName = "";

, C-ish, , if(), true, () . , . , , .

+8

- . static, .

, , , , " ", " ". , .

, , , , , ; , .., ​​ : .. .

+5

.

, , . .

+1

, #, if . , if, . , . , , .

+1

, , .

if # (++, c). . .

+1

. _dbName , Program, InitVars() .

If each instance Programhas the same value for _dbName, then it _dbNameshould be marked as static. If different instances can have different values, then it InitVars()must be an instance method (delete the static keyword and only call it on the real objects of the program, and not on the static Main).

0
source

"static" in VB will be "general."

0
source

Source: https://habr.com/ru/post/1760380/


All Articles