Static Constructor and normal Constructor
Most of the people are getting getting lots of confusion on Static Constructors. Today i want write my views on static constructors in .net.Can we declard constructor as Static?
Yes.
Can we declare Constructor as Private?
Yes. Go through Singleton Design Pattern.
What are differences between Normal and Static Constructors in .net?
Normal Constructors:
1. Used for initialize class variables.
2. Normal constructors are instance level.
3. For every time of object initialization constructor will call.
Static Constructors:
1. Used for initialize class level static variables.
2. Static constructors can't accept any other objects other than static like static methods. If we write also compile time errors will come. like "An object reference is required for the non-static field, method, or property 'ConsoleApplication1.staticClass.strName'ConsoleApplication1\StaticConstructor.cs"
3. These are very similar to static methods, like static constructors are class level not instance level.
4. Static constructors are called only once.
5. Static constructors will not take any kind of access modifiers like private, public, internal ...
Static constructor have Access Specifiers or not?
No, static constructors shouldn't have access specifiers. Those are strictly private.
Can static constructors have arguments ?
static constructors don't take any arguments.
What is the level of access for Static constructor, if class will public?
This time also private only like normal constructor.
When we will use static constructor, what is the use of that?
Based on requirement like whenever we want to initialize static variables. which needs to be execute once, that time we will use this static constructor.
Write one example for Static Constructor?
In this example static constructor called only once:
output of the program is : http://aspnettutorialonline.blogspot.com/
Number of times called: 1
class StaticConstructor { static void Main(string[] args) { Console.WriteLine("http://aspnettutorialonline.blogspot.com/"); staticClass objStatic = new staticClass(); staticClass objStatic1 = new staticClass(); staticClass objStatic2 = new staticClass(); string str=objStatic.Reply(); Console.WriteLine(str); Console.ReadLine(); } } class staticClass { static int i; static string strName; static staticClass() { i ++; strName = "Number of times called: "; } public string Reply() { return strName+" "+i.ToString(); } }
See more OOPS DOTNET Interview Questions
See more ASP.NET, C#.NET, SQL Server and more Interview Questions
Post a Comment
Please give your valuable feedback on this post. You can submit any ASP.NET article here. We will post that article in this website by your name.