Click here to Skip to main content
15,913,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI,
I know this is a basic question but i need some depth details
Why i could not able create objects for the non static class in the static method?

Fo ex:
In this following code and getting "inaccessible due to its protection level" error ...
Please explain..


C#
namespace dotnetfunda_ex1 { 
public class ClassA 
{ 
ClassA(int var) 
{ } 

public static void tm() 
{ } 

} 

class Program 
{ 

public static void Main(string[] args) 
{ 
ClassA obj = new ClassA(1); 
//obj.tm(); 

} 
} 


} 



Manikandan Muthuraj

Thanks & Regards,
Manikandan Muthuraj
http://talkheredotnet.blogspot.com/
Posted
Comments
I guess you can't access static member function of one class from another.

You cannot access a static field/method/property from an instance of the given class.
It means, if you want to access it (and its access modifier allows you to do it), you have to use the class itself rather than an instance of it.

Thus, this would turn your
obj.tm();

to
ClassA.tm();


Hope this helps.
 
Share this answer
 
The code you show will not compile - not because of a protection level, but becasue you must declare constructors with an appropriate protection declaration: public or private for example:
C#
public class ClassA
    {
    public ClassA(int var)
    { }
    public static void tm()
    { }
    }

class Program
    {
    public static void Main(string[] args)
        {
        ClassA obj = new ClassA(1);
        //obj.tm();
        }
    }
If you then uncomment your tm method access, you will get a different error:
cannot be accessed with an instance reference; qualify it with a type name instead
because it is a static method - and you need to access those via the Class name instead:
C#
public static void Main(string[] args)
    {
    ClassA obj = new ClassA(1);
    ClassA.tm();
    }


[edit]Typos - twice - I hate IE, I hate IE... - OriginalGriff[/edit]
 
Share this answer
 
v3
This compile-time error means that the property you are trying to access is not public and the only way to access it is by either modifying its access modifier or using reflection.

When it's not visible enough to reach: If, for example, the class is in another project and the visibility is interal or lower (protected or private), you won't be able to use it. You'll have to change it to public in such a case:

C#
public class ClassA
    {
    public ClassA(int var)
    { }
    public static void tm()
    { }
    }

class Program
    {
    public static void Main(string[] args)
        {
        ClassA obj = new ClassA(1);
        //obj.tm();
        }
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900