0

In windows Form App I get call

  private Class1 c1;
  private void Print()
  {
            c1 = new Class1();
  }

but in next one i don't want to declare new Class because it make a wrong value for my program and get error. it's like

  private void Print2()
  {
            c1 ; //**( I don't want to declare new one )**
  }

edit 2 i'd like to do like you said but argument in my code is like

    public CandleCollection GetCandleCollection()
    {
        CandleCollection collection = null;
        try
        {
            collection = SymbolList[cbxSymbol.Text];
        }
        catch (Exception) { }
        return collection;
    }       
    private Class1 c1 = new Class1(<collection>);  **it's need to call collection**
    private void Print()
    {
            c1 = new Class1();
    }
    private void Print2()
    {
            c1 ; //**( I don't want to declare new one )**
    }

edit 3 This is my original code to call c1

    private void Print()
    {
        CandleCollection collection = GetCandleCollection();
        Class1 c1 = new Class1(collection);
    }
Mac N.
  • 51
  • 7
  • `private Class1 c1 = new Class1();`? – Patrick Hofman Aug 02 '17 at 08:38
  • What is the funtionality that you want to achieve? I don't quite get it... – Peter Aug 02 '17 at 08:39
  • What's your problem exactly? – Mafii Aug 02 '17 at 08:39
  • do want it to be singleton then make it a prop and check if the private variable assigned to property has been initiated if not then only initiate it. https://stackoverflow.com/questions/2155688/what-is-a-singleton-in-c – Anil Aug 02 '17 at 08:39
  • Presuming that Print() and Print2() are in the same class, you need to read about properties in C#. – marcushobson Aug 02 '17 at 08:39
  • Use different Constructors then? – waka Aug 02 '17 at 08:40
  • You're confusing declaration and definition. `c1` is declared as a field in the class, and initialised in `Print`. It will still exist in `Print2`, no need to initialise it again. – Luaan Aug 02 '17 at 08:40
  • in my example. yes it can . but in my code it's like private Class1 c1 = new Class1( something inside ); – Mac N. Aug 02 '17 at 08:41

1 Answers1

1

Move your CandleCollection variable out of the public method so you can also use it out of this method.

Then, you can instantiate the Class1 variable only once:

private CandleCollection collection = null;

public CandleCollection GetCandleCollection()
{
    try
    {
        collection = SymbolList[cbxSymbol.Text];
    }
    return collection;
}       
private Class1 c1 = new Class1(collection);
private void Print()
{
        c1;
}
private void Print2()
{
        c1;
}
Koby Douek
  • 16,156
  • 19
  • 74
  • 103