Search code examples
c#syntaxinstance

Why I can't make instance outside of method


using System;

namespace FileApp
{

    public class status
    {
        public int speed;
    }

    public class Player
    {
        private status ddd = new status();
        ddd.speed = 3;


        static void Main()
        {
            status dd = new status();
            dd.speed = 3;
        }
    }

}

Why I can't use ddd.speed? Why I can't set ddd.speed to 3? Please help me..


Solution

  • Because logical statements like that belong in a method, not in the class definition. The class definition can define class members (fields, properties, methods), but not perform imperative logic.

    In your Main method you already show how to do this:

    status dd = new status();
    dd.speed = 3;
    

    Now, if you specifically want to access ddd in your Main method, take note of the fact that Main is static and therefore not associated with any given isntance of Player. So you'd need an instance:

    Player player = new Player();
    

    And since ddd is private, you'd want something to allow you to access that field. A property is useful for that sort of thing. For example, define it as:

    private status ddd = new status();
    public status DDD { get { return ddd; } }
    

    Which you could also shorten to simply:

    public status DDD { get; private set; } = new status();
    

    Then you can access it on your instance:

    Player player = new Player();
    player.DDD.speed = 3;