[RESOLVED] [2.0] Error In static Function
Hi all :wave:
check out the class I am using static function in it.
C# Code:
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..
C# Code:
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
Re: [2.0] Error In static Function
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
Re: [2.0] Error In static Function
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.
Re: [2.0] Error In static Function
Page not opening
Quote:
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
Re: [2.0] Error In static Function
There was something wrong with the link. I have edited my post above.
Re: [2.0] Error In static Function
Re: [2.0] Error In static Function
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
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.
Re: [2.0] Error In static Function