Home Assigning of variables in parent class in c#
Reply: 1

Assigning of variables in parent class in c#

Mr. Knackwurst
1#
Mr. Knackwurst Published in 2018-02-11 10:19:26Z

I’m working with a state pattern and are wondering how to define variables so they can use in each child class. A protected variable in the abstract parent class may be the right choice, but with this, I’m wondering how to initialize these variables from the main class.

class Main
{
    \\Initialize variable "file" here?  
    \\...
            Context tc = new Context(new Step01());
    \\...
}


class Context
{
    private State ts;

    // Constructor
    public Context(State st)
    {
        this.State = st;
    }

    // Gets or sets the state
    public State State
    {
        get
        {
            return st;
        }
        set
        {
            st = value;
        }
    }

    public void Request()
    {  
       ts.Handle(this);
    }
}


abstract class State
{
    protected string file = "file";
    public abstract void Handle(Context tc);
}

class Step01 : State
{      
    tc.State = new Step02();
    // use variable "file"
}

class Step02 : State
{   
    tc.State = new Step0x()   
    // use variable "file"
}

The example is a code snipped and don't work. I hope it helps to explain my question more accurate.

The quantity of child classes (Step0x) varies, so I think it's easier to define the variable only once in the parent class.

Does anybody have an idea how to initialize my variables in the main class?

Thank you.

Alex
2#
Alex Reply to 2018-02-11 12:42:57Z

Define file as constant:

abstract class State
{
    protected const string file = "file";
    public abstract void Handle();
}

Here is implementation of Step01 and Step02 which are using file:

class Step01 : State
{
    public override void Handle(){}            

    public void PrintFile()
    {
        Console.WriteLine(string.Format("step1 + {0}", file));
    }
}

class Step02 : State
{
    public override void Handle(){}

    public void PrintFile()
    {
        Console.WriteLine(string.Format("step2 + {0}", file));
    }
}

And here is usage of the Step01 and Step02 classes:

static void Main(string[] args)
{
    Step01 step1 = new Step01();
    step1.PrintFile();
    Step02 step2 = new Step02();
    step2.PrintFile();
    Console.ReadLine();
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.391026 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO