I created a class with 6 private static methods and a private constructor. The private constructor runs all of the static methods. I want to call the class's private constructor in another class, but I'm not able to. All I want is to run this class once without creating an instance of anything. The class populates a small database and I have no need for it other than calling it once.
I could put it into a method, but I don't want to put unrelated code into my main class. I want everything more separated. I could just do it with a public constructor and create an instance of the class, but I don't see why I would have to do it that way when an instance isn't needed.
Is there a good way to accomplish what I'm trying to do?
Why not replace your private constructor with a public static method?
Your original code:
public class DatabaseInitializer
{
private DatabaseInitializer()
{
init1();
init2();
...
}
private static void init1() { ... }
private static void init2() { ... }
...
}
Your new code
public class DatabaseInitializer
{
public static void Init()
{
init1();
init2();
...
}
private static void init1() { ... }
private static void init2() { ... }
...
}
Than you call it:
Main()
{
DatabaseInitializer.Init();
}
Singleton would make exact one Instance. If you don't want an Instance, just make one static method public. If you want to make sure this is called only once make a static counter or a bool in your class which stop the method from being called a second time
call constructor without an instance is impossible, even if it was public
I want to call the class's private constructor in another class
--
All I want is to run this class once without creating an instance of anything
If you do not want to create an instance of your class, then do not use the constructor. I think you just want to use a class to "separate" some code? Use a static method for that.
Or if this code should run once and call some static methods. You can use a static ctor
class B
{
static B() {
//this stuff called when you create this class or when a static member is referenced
}
IMHO, this is not an unrelated code for main class. It's dependent on these methods.
You could just have one public method in the class. Dependent classes can then call that method which in turn calls all the private methods doing processing.
If you want to call it or its members from another class, you will need to make a public method.
If you don't want any instances of this class around, then you should make a public static method that can be called.
The public static method should have a static boolean. When called, it checks that value, and if not set, switches the static boolean value (so it knows it has been called before) and then calls all the private static methods that need to be run once and only once.
If you only need this initialization done once ever to the database, rather than once per effort, then you should have your static code run out and check the database to see if it has already been initialized. You could make this particularly easy by having a one row table that holds a boolean in it that you can test. Just update the initialization code to set that value when the DB is initialized, and have your start up code test for that value to determine its value and what actions to take based upon that value.
Related
I have a helper class that takes some object, processes it and returns back some instance of the other class or even the List of the objects.
What would be the best way: to make this helper method static or non-static?
The thing is that my app can create lots of the Car objects and I was thinking whether it could have a negative effect when each of them use the static helper?
Probably this is something that can be solved without deciding the helper object's life-cycle where you require it.
You should try to leverage dependency injection approach:
public class X
{
public X(IHelper helper)
{
Helper = helper;
}
private IHelper Helper { get; }
public void DoStuff()
{
var result = Helper.DoOtherStuff(input);
}
}
That is, X don't know whether Helper is always the same instance or if it's a transient object. This makes the code cleaner and more test-friendly, because you can mock the helper with a fake IHelper implementation to be sure that you're just testing X.
Most helper or utility classes use static methods. You should only use non-static methods if you want to create multiple instances of your helper class, but since you just need a simple input -> function -> output, I would make the methods static.
Use static class with static methods, No instance, no derivation and only static methods in the class.
public static class HelperClass
{
public static void HelperMethod()
{
// do something
}
}
I stumbled upon a problem where i need an instance of the class inside its static constructor. I believed it was not possible to do it so i tried the following:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Foo.someString);
Console.ReadLine();
}
}
class Foo
{
public static readonly string someString;
static Foo()
{
someString = new Foo().CreateString();
}
private string CreateString()
{
return "some text";
}
}
To my surprise, it works - the output is "some text". I believed the static constructor must run and complete before instances of the class can be created. This answer shows that this is not necessarily the case. Does this mean that static and instance constructors are independent of each other? And finally, is it safe to do this (create instances in static constructor)?
p.s. Let's ignore the fact that this can be avoided by using a different approach.
All that the specification says is that the static constructor will be called before any instance of the class is created. But it doesn't state anything about the fact that this constructor must finish:
A static constructor is used to initialize any static data, or to
perform a particular action that needs to be performed once only. It
is called automatically before the first instance is created or any
static members are referenced.
You could perfectly fine create instances of the class inside the static constructor and this is safe.
It is safe as it will be called only once.
Static constructor called automatically before the first instance is created or any static members are referenced any static fields are referenced. Hence when your application ran and you accessed Foo, the static constructor was executed and your string was initialized.
Is it safe ? : As such there is no harm in doing this. It is just they are executed only once.
For information on this read Static Classes and Static Class Members on MSDN
Here is a piece of code:
private class myClass
{
public static void Main()
{
}
}
'or'
private class myClass
{
public void method()
{
}
}
I know, first one will not work. And second one will.
But why first is not working? Is there any specific reason for it?
Actually looking for a solution in this perspective, thats why made it bold. Sorry
It would be meaningful in this scenario; you have a public class SomeClass, inside which you want to encapsulate some functionality that is only relevant to SomeClass. You could do this by declaring a private class (SomePrivateClass in my example) within SomeClass, as shown below.
public class SomeClass
{
private class SomePrivateClass
{
public void DoSomething()
{
}
}
// Only SomeClass has access to SomePrivateClass,
// and can access its public methods, properties etc
}
This holds true regardless of whether SomePrivateClass is static, or contains public static methods.
I would call this a nested class, and it is explored in another StackOverflow thread.
Richard Ev gave a use case of access inside a nested classes. Another use case for nested classes is private implementation of a public interface:
public class MySpecialCollection<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
return new MySpecialEnumerator(...);
}
private class MySpecialEnumerator : IEnumerator<T>
{
public bool MoveNext() { ... }
public T Current
{
get { return ...; }
}
// etc...
}
}
This allows one to provide a private (or protected or internal) implementation of a public interface or base class. The consumer need not know nor care about the concrete implementation. This can also be done without nested classes by having the MySpecialEnumerator class be internal, as you cannot have non-nested private classes.
The BCL uses non-public implementations extensively. For example, objects returned by LINQ operators are non-public classes that implement IEnumerable<T>.
This code is syntactically correct. But the big question is: is it useful, or at least usable in the context where you want to use it? Probably not, since the Main method must be in a public class.
Main() method is where application execution begin, so the reason you cannot compile your first class (with public static void Main()) is because you already have Main method somewhere else in your application. The compiler don't know where to begin execute your application.
Your application must have only one Main method to compile with default behavior otherwise you need to add /main option when you compile it.
I heard that a private constructor prevents object creation from the outside world.
When I have a code
public class Product
{
public string Name { get;set;}
public double Price {get;set;}
Product()
{
}
public Product(string _name,double _price)
{
}
}
Here I still can declare a public constructor (parameter), won't it spoil the purpose of the private constructor? When do we need both private and public constructor (parameter) in code?
I need a detailed explanation please.
The reason you would use the pattern you're describing is when you want to control how the object is instantiated.
In your example, for instance, you're saying the only way to create a Product is by specifying its name and price. This is with respect to the outside world, of course. You could also do something similar using other access modifiers, and it would have different implications, but it all boils down to controlling how you want the objects instantiated with respect to who will be doing it.
If you wanted to prevent object creation altogether you would have to make all your constructors private (or protected). That would force the object to be created from within itself (or an inherited class).
Also, as Matti pointed out in the comment below, when you define a constructor that is parameterized you don't need to specify a private default constructor. At that point it is implied.
Constructors can be chained together to avoid having to duplicate code. It is quite common to have private constructors, that nobody is supposed to call outside of the class, that are chained from a public constructor.
Example:
public class Test
{
private Test(int? a,string b) { }
public Test(int a) : this(a, null) { }
public Test(string b) : this(null, b) { }
}
Here there are two public constructors, one taking a string and one taking an int. They both chain to the common private constructor that takes both arguments.
Also, you can construct new objects from within the same class by using the private constructor. For instance, when you want specialized constructors only available through static factory methods:
public static Test Create()
{
int? a = ReadConfigurationForA();
string b = ReadConfigurationForB();
return new Test(a, b);
}
When it is not be a good idea to expose a private constructor to the outside world, add a static factory method that fetches the correct arguments to pass on the constructor.
You need a private constructor when you only want that constructor to be called from within the class itself. In your example you are forcing the calling object to provide 2 parameters when creating the object.
With a private constructor you could do something like:
public static GetInstance ()
{
return new YourObject();
}
but nothing else except the object could call the parameterless constructor.
It's commonly used to create a singleton pattern:
http://www.dofactory.com/Patterns/PatternSingleton.aspx
You would use a constructor with parameters when you wanted to force calling code to pass a value to the constructor in order to create an instance of your class. In your example, calling code must use the parameter version of the constructor in order to create a Product.
A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
For more details refer to this:
http://msdn.microsoft.com/en-us/library/kcfb85a6(VS.80).aspx
Does each static call will initiate a new thread?
For E.g.:
class A
{
public static void displayName()
{
Console.WriteLine("myName");
}
public static void displayAge()
{
Console.WriteLine("myAge");
}
}
class B
{
public void Foo()
{
A.displayName();
A.displayAge();
}
}
Will the above calls runs independent of each other? If yes, then, is it something similar to Threading?
Reply to your doubt regarding static call:
But i heard each static call is
independent of each other as there is
no instance and only static members
are involved. is it so? – Sri Kumar 36
mins ago
You can think there is a 'global' instance of your class, and all static methods are held by this instance.
As in your example, you can create a 'user' instance by calling ClassA myA = new ClassA(). Meanwhile, there will be a 'global' instance, which is created by the runtime but invisible to you, and static methods reside in this instance. Static methods behavior as instance methods within this 'global' instance.
Amazingly, in C# there is a static constructor, which will be called when the 'global' instance is initialized by the runtime.
You can test this code:
class A
{
static A() {
Console.WriteLine("Creating the global instance of class A....");
}
public static void displayName()
{
Console.WriteLine("myName");
}
public static void displayAge()
{
Console.WriteLine("myAge");
}
}
class B
{
public void Foo()
{
A.displayName();
A.displayAge();
}
}
The output will be:
Creating the global instance of class A....
myName
myAge
Apart from this, static methods have nothing difference from instance methods.
Variables in each static method will have its own scope, and they are independent from one method to another method.
No they will run sequentially on the same thread
No. Static methods are like any other methods unless you invoke them in different threads they will run in same thread from which you have invoked.
It really depends on where do you invoke. Static methods itself does not create any threads and run within.
A static method is a method that does not have any class associated with it. This means that calling a static method does not have to go through any indirection, unlike a virtual method which is resolved based on the object it is called on.
All methods will run on the thread of the invoking method, whether virtual or static. If you want a method to run on a different thread, use the thread pool or some other technique.
One more thing:
i heard each static call is independent of each other
Static method calls are not really independent.
Static method can still access other static fields and properties within the same class, or publicly visible static fields and properties of other classes, which are also global and retained during the lifetime of your app.
Static methods which are changing the state of static fields are not "independent", as you suggested. The only thing you can say for sure that they are always invoked on a single instance (always using the same private data).