none
Call a method inside the same class (Recursive Loop Problem)

    Question

  • I have created a class that defines several properties that all get their values from methods in the same class. The problem is that it is a recursive loop because I am trying to create an instance of the class, which then creates a new instance over and over. I want to know how to just directly reference my method without creating a new class instance for it.

    My Code:

    public class MyProperties
    {
       public int Value1 {get; private set; } = new MyProperties().SetValue("Value1"); //This is a recursive loop
       public int Value2 {get; private set; } = new MyProperties().SetValue("Value2"); ////This is also a recursive loop
    
       //The method to get the values
       public int SetValue (string MyValue)
       {
          if (MyValue == "Value1")
          {
             return 1;
          }
          else if (MyValue == "Value2")
          {
             return 2;
          }
       }
    }

    So instead of doing:

    new MyProperties().SetValue("blah blah blah");

    I want to do something like:

    new SetValue("blah blah blah");




    • Edited by Varscott11 Tuesday, April 11, 2017 4:47 PM
    Tuesday, April 11, 2017 4:37 PM

Answers

  • Try the next way of direct referencing:

    public class MyProperties

    {

           public int Value1 { get; private set; } = SetValue( "Value1" );

           public int Value2 { get; private set; } = SetValue( "Value2" );

           static int SetValue( string MyValue )

           {

                  if( MyValue == "Value1" )

                  {

                         return 1;

                  }

                  else if( MyValue == "Value2" )

                  {

                         return 2;

                  }

                  . . .

                 

           }

    }

    • Proposed as answer by Ryan Software Tuesday, April 11, 2017 6:21 PM
    • Marked as answer by Varscott11 Tuesday, April 11, 2017 7:10 PM
    Tuesday, April 11, 2017 6:18 PM