Reputation: 9025
Is there a way to assign a default method to a class like this:
public class EscMenu
{
public static void EscMenu()
{
//do something
}
public static void SomeOtherMethod()
{
//do something else
}
}
So when I call EscMenu.SomeOtherMethod();
in another class in the same solution, it does "do something else", but I cannot call EscMenu();
.
How can I do that?
Thanks!
EDIT:
Okay, Im gonna try to explain this in a better way:
I just want the class EscMenu
to do something when I call it from another (external) class like this: EscMenu();
. Of course I could easily create a method default()
in EscMenu
and call EscMenu.default();
externally. But I would really like to just call EscMenu();
If that just isn't possible or I continue to fail in explaining myself, then just don't mind ;-)
Thanks again!
Upvotes: 3
Views: 8163
Reputation: 45172
What you have there (if you cleaned up the syntax) is a static constructor.
- A static constructor does not take access modifiers or have parameters.
- A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
- A static constructor cannot be called directly.
- The user has no control on when the static constructor is executed in the program.
Upvotes: 0
Reputation: 11770
I don't knwo what you mean with default method. But to prevent other classes to call methods in your class ExcMenu, you can make your method private:
public class EscMenu
{
private static void EscMenu()
{
//do something
}
public static void SomeOtherMethod()
{
//do something else
}
}
Upvotes: 0
Reputation: 45068
The concept of a "default" method is a kind of absurdity in C#, but from what I can glean from your requirements, you don't want to be able to call EscMenu
externally (i.e outside of the class), so for that use the private
access modifier:
private static void EscMenu(){
//do something
}
But you would need a distinct name for the member.
Upvotes: 0
Reputation: 1503290
No, you can't give a method the same name as its containing type - and you really don't want to confuse the name of a type with the name of a method anyway. Why introduce the ambiguity?
If you could give some example where you want to write code in some way other than what's already available, we may be able to help you more. (For example, it may be that extension methods could help.)
Upvotes: 7