8

I have a number of classes in a Classes file, and I want them all to be able to access the same, global method to save duplicating code. Problem is, I can't seem to access a method from another class in my file - any ideas?

So my class1.cs layout is similar to this:

public class Job1 { public Job1() { } } public class Methods { public static void Method1() { //Want to access method here from Job1 } } 
3
  • 2
    Did you try Methods.Method1()? Commented Nov 3, 2010 at 19:20
  • 2
    IMO you must read some oop article. Commented Nov 3, 2010 at 19:24
  • Seems like you're new to OOP. Not a bad thing, everyone's gotta start somewhere. You'd do good to read an OOP book alongside coding to get some fundamentals that are very important to all OOP languages. Commented Nov 3, 2010 at 19:28

3 Answers 3

11

You'll need to specify the class they are in. Like this:

public Job1() { Methods.Method1() } 

If the class Job1 is in a different namespace from Methods then you'll need to either add a using clause, or specify the the namespace when calling the method. Name.Space.Methods.Method1()

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, I feel extremely stupid. Was sure that didn't work when I tried it before. Ah well, works great now - cheers buddy!
1

Actually. Public Job1(){} is a constructor and not a method. It can be called from main class by creating object form the JOB1 class. Here add the following code:

public static void method1() { Job1 j1=new Job1(); } 

constructor can be invoked by creating a object to the corressponding class....

Comments

0

To access methods of other classes, the methods must be static with a public Access modifier.

static - Not bound to an instance of the class but shared by all other instances.

private - data can only be accessed from inside the same class.

public - data can be accessed from other classes but must be referenced.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.