Learners question: Static methods

  • Thread starter Thread starter Madhu
  • Start date Start date
M

Madhu

Hi all,

I am new to c#. I was trying out the following:

class A
{
private static void doSomething()
{
System.Console.WriteLine("Class A is doing something");
}
}

class B
{
private static void Main()
{

A.doSomething();
}
}


If I compile the above code, I get the following error:

error CS0122: 'A.doSomething()' is inaccessible due to its
protection level

If I remove the private keyword from the method doSomething() in class A,
the file gets compiled without errors.
The error is clear to me. But what is not clear is why the compiler does not
give error for the method Main(). It is also a static method which I have
decleared private which should mean its not accessible to anybody.

Thanks in advance,
Madhu.
 
Sorry, I forgot to mention in my mail that the code gets compiled only if I
specify public keyword.
 
Madhu said:
Sorry, I forgot to mention in my mail that the code gets compiled only if
I
specify public keyword.

news:[email protected]...

I found such explanation of fact that
private static int Main() works.

"Author:Roy Fine ([email protected])
Topic:Re: private static void Main()
News grup: microsoft.public.dotnet.languages.csharp
Date:2004-03-07 10:38:33 PST


Sujala,

public, private, protected and others are access attributes that are
enforced primarily by the compiler (at runtime only when dynamic invocation
is involved). Beyond that, the runtime is free to accept or ignore the
access specifiers - and in the case of Main, it kindly ignores them.

Matters such as these (and this is but one example of many others) are
implementation specific details for the runtime, not for a particular
language.

regards
roy fine
"
 
Madhu said:
Sorry, I forgot to mention in my mail that the code gets compiled only if
I
specify public keyword.

I'm still learning all this stuff, but I'll give it a shot...

Declaring the Main method as private static should indicate that is
available to other members of the type containing Main. However, declaring
your type as private static would make the type and all of its members
completely inaccessible.

carl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top