Reputation: 488
As i searched and got few points static class is sealed and uses private constructor internally then why in my code i am not able to access the method using the class name using System?
using System;
public sealed class ClasswithPrivateCons {
private ClasswithPrivateCons() { }
public void Printname() { Console.WriteLine("Hello world"); }
}
public class Program {
public static void Main() {
ClasswithPrivateCons.Printname(); // gives error
}
}
Upvotes: 1
Views: 330
Reputation: 1407
public sealed class ClasswithPrivateCons
{
public ClasswithPrivateCons() { }
public void Printname() { Console.WriteLine("Hello world"); }
}
class Program
{
static void Main(string[] args)
{
ClasswithPrivateCons cl = new ClasswithPrivateCons();
cl.Printname();
}
}
Also Printname
method can be declared as static. Than it may be called
ClasswithPrivateCons.Printname();
Upvotes: 1
Reputation: 169398
It would be useful if you also included the error you're getting, but in this case it's obvious: Printname
is not a static method, so you can't call it without an instance of ClasswithPrivateCons()
. Since that constructor is private, you can't construct those objects.
Three resolution options:
Printname()
static; then ClasswithPrivateCons.Printname()
will worknew ClasswithNoLongerPrivateCons().Printname()
will workpublic static ClasswithPrivateCons New() { return new ClassWithPrivateCons(); }
ClassWithPrivateCons.New().Printname()
Upvotes: 3