user1166981
user1166981

Reputation: 1746

Calling a function from within another function?

I want to use a function from another class within a new function which I will call from main. I am trying to do this as below, but get an error:

Error The name 'Class1' does not exist in the current context.

Actually, in my code I use different names, but its just to illustrate the structure and to make it easier to read for you.

public class Class1
{      
    public static int[] Function1()
    {
       // code to return value
    }
}


public class Class2
{ 
      public static int Function2()
      {
         int[] Variable = Class1.Function1();
         //other code using function1 value
      }
}

Upvotes: 0

Views: 249

Answers (1)

Ed Swangren
Ed Swangren

Reputation: 124790

Actually, in my code I use different names, but its just to illustrate the structure and to make it easier to read for you.

Unfortunately you've made it so easy to read that you have eliminated the problem entirely! The code you posted does not contain an error and is perfectly valid.

The error message is very clear; from wherever you are actually calling the code, "Class1" (or whatever it may be) is not in scope. This may be because it is in a different namespace. It may also be a simple typo in your class name. Does your code actually look something like this?

namespace Different 
{
    public class Class1
    {      
        public static int[] Function1()
        {
           // code to return value
        }
    }
}

namespace MyNamespace
{    
    class Program
    { 
          static void Main(string[] args)
          {
              // Error
              var arr = Class1.Function();

              // you need to use...
              var arr = Different.Class1.Function();
          }
    }
}

That's the best I got until you post the actual code.

Upvotes: 5

Related Questions