Possible Duplicate:
What is the difference between Public, Private, Protected, and Nothing?
I have a question : What is the difference between these method types ?
Static , Public , Internal , Protected , const , void
Sorry my question may seem awkward to professionals but i really want to understand the difference , and by the way i searched and read articles about them but they are all big and not well described , i just need a nice example for each so i could make decision each time i make a function , because i always start with private void ........
Your basic method has the following:
[access modifier?] [static?] [return type or void] [name] ([parameters?])
There's a few extra bits and pieces but that's your start.
Access Modifiers
Some of those are access modifiers which control which classes have access (can call) whatever you've put the modifier on.
// Anyone can call me
public int SomeMethod() { return 1; }
// Only classes in the same assembly (project) can call me
internal int SomeMethod() { return 1; }
// I can only be called from within the same class
private int SomeMethod() { return 1; }
// I can only be called from within the same class, or child classes
protected int SomeMethod() { return 1; }
Static
Static
means that the method/variable is shared by all instances of the class. It can be combined with an access modifier from above.
public class Test
{
static int a = 0;
public int SomeMethod() { a = a + 1; return a; }
}
Test t1 = new Test();
t1.SomeMethod(); // a is now 1
Test t2 = new Test();
t2.SomeMethod(); // a is now 2
// If 'a' wasn't static, each Test instance would have its own 'a'
Void
void
just means that you have a method that doesn't return anything:
public void SomeMethod()
{
/* I don't need to return anything */
}
const
const
means that the variable cannot be modified:
const int LIFE = 42;
// You can't go LIFE = 43 now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With