share
Stack OverflowCannot call method in another class
[-14] [2] The Brajraj
[2010-07-21 20:10:48]
[ c# ]
[ http://stackoverflow.com/questions/3303389] [DELETED]

I have defined a method in a class and am trying to create an instance of the class and then call the method, except it will not compile. What am I doing wrong?

using System;
class Method
{
  int Cube ( int x )
  {
    return ( x*x*x );
  }
}

class MethodTest
{
  public static void Main()
  {
    Method M=new Method();
    int y = M.Cube (5);
    Console.WriteLine(y);
  }
}
(5) What are we? Your compiler? - Brian Genisio
(8) You've got middle-management written all over you. - George
(6) Find the lack of interest on our part and fix it. - Adam Crossland
(3) It is definitely a trivial question, but since when has SO prohibited questions of this kind. Sure, a little more information would have been nice to include, but -10 is a little punitive is it not? Nothing says welcome to SO like a -10. - Brian Gideon
(10) @Brian Gideon, to be fair to the community, 9 of the downvotes were accumulated when the title was "find error and fix it" and there was no text accompanying the code sample (which also was not originally formatted). - Anthony Pegram
@Anthony: Good point. I see that the only reason it looks halfway reasonable is because you edited it :) - Brian Gideon
Did you received any error message from your compiler ? - Mike Verrier
[+6] [2010-07-21 20:14:28] IVlad

the Cube method is private by default. You need to qualify it as public.


hmm..but it no works..give error." 'Method.Cube(int)' is inaccessible due to its protection level" - The Brajraj
(4) @The Brajraj, you have to want it more. - Anthony Pegram
(1) ... which is why you should make the Cube method public: public int Cube(int x) { ... } - IVlad
@The Brajraj: Wrong. public int Cube(int x) works. @IVlad is correct. - Brian Genisio
@Anthony, yes, fix it.. - The Brajraj
it works...thanks to all - The Brajraj
(1) ... script kiddies... - Brian Genisio
1
[+4] [2010-07-21 20:15:24] Anthony Pegram

Your Cube method has no access modifier, which means it is implicitly private. Change the signature to public int Cube(int x) and retry.


2