PDA

Click to See Complete Forum and Search --> : [RESOLVED] [2.0] Error In static Function


shakti5385
Apr 16th, 2007, 12:59 AM
Hi all :wave:
check out the class I am using static function in it.
class sample
{
int i;
static int count = 0;
sample()
{
i = 0;
count++;
}
static void ShowCount()
{
Console.WriteLine(count);
}
}

But When I am calling the object of the class I am getting error at the underline part..class Program
{
static void Main(string[] args)
{
sample s1=new sample();//First Error
sample.ShowCount(); //Second Error
}
}

The error saying that
1)'sample.sample()' is inaccessible due to its protection level
2)'sample.ShowCount()' is inaccessible due to its protection level

So what is the problem , what I am doing wrong here.
Thanks

Shuja Ali
Apr 16th, 2007, 01:12 AM
In C# the default access modifier is Private. In your case you have not explicitly mentioned the access modifier so it is private by default, which in turn means that the methods cannot be called from outside the class.

Read about access modifiers here
http://msdn2.microsoft.com/en-us/library/ms173121.aspx

penagate
Apr 16th, 2007, 01:15 AM
Also, count++ needs to be sample.count++.

I strongly recommend using uppercase for class names (Sample rather than sample) so that you do not muddle them with variables.

shakti5385
Apr 16th, 2007, 01:17 AM
Page not opening

I strongly recommend using uppercase for class names (Sample rather than sample) so that you do not muddle them with variables.

That I forget :)
OK

Shuja Ali
Apr 16th, 2007, 01:25 AM
There was something wrong with the link. I have edited my post above.

shakti5385
Apr 16th, 2007, 04:57 AM
Not get the solution.

Shuja Ali
Apr 16th, 2007, 05:05 AM
The methods in your class do not have an access modifier and in C# when you do not provide an access modifier, the default modifier (which is private) will be used. So in your case both your constructor and the static method are private and you cannot access anything that is private from outside the class. Here is the modified code class sample
{
int i;
static int count = 0;
public sample()
{
i = 0;
count++;
}
public static void ShowCount()
{
Console.WriteLine(count);
}
} Also the link that I posted above will explain you what access modifiers are and how to use them.

shakti5385
Apr 16th, 2007, 05:23 AM
Thanks sir