1

I use Resharper tool in visual studio

Consider a very simple class written below.

class Test()
{

   //constructors do not have any return type.   
   Test()
   {
      System.Console.WriteLine("Hello World!");
   } 

   static Test()
   {
        System.Console.WriteLine("Hello World in Static constructors");
   }

   public void A()
   {
      System.Console.WriteLine("A simple function in a class");
   }

}


class Program
  {
    static void Main(string[] args)
    {
        var asa = new Test(); //Implicitly Typed local variables.
        asa.A();

    }
}

Using var (the compiler has to infer the type of the variable from the expression on the right side of the initialization statement).

I have some clarification questions and they are below.

  1. Extra burden to compiler?
  2. How many constructors a class can have?
  3. Why is static constructor called first ? (I checked out by putting a breakpoint?)
  4. Why not Test asa = new Test(); is not preferred by Resharper?
  5. Is it really a good idea to use Resharper first as a beginner? (Myself being a newbie to C and .net programming!)

Thanks in Advance.

  • 3
    Please ask one question at a time. Also, try to find answers by yourself first and explain why you couldn't find anything. The answers to these questions should be available in many places online, and some clues are even available based on thinking about them yourself. – O. R. Mapper Sep 17 '12 at 06:06

4 Answers4

7
  1. Any extra burden to the compiler is basically irrelevant - it should not be part of your decision about whether or not to use var. As noted in comments, it may well require slightly more work for the compiler when you use explicitly declared variable... but again, it's not going to be significant.

  2. A class can have any number of constructors... although it will become unwieldy pretty quickly.

  3. The static constructor will be called once, before the first use of the class (whether that's via a static method or a constructor call). Read the C# spec for more details - section 10.12 of the C# 5 spec includes:

    The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

    • An instance of the class type is created.
    • Any of the static members of the class type are referenced.
  4. You can configure ReSharper to suggest alternatives, or treat them as warnings, etc. Make it work however you think it should, on this front.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • It seems to me that there's actually more burden on the compiler with an explicitly typed variable. In both cases, the compiler must determine the static type of the right side of the assignment, but with an explicitly typed variable, it must also decide whether that type is implicitly convertible to the variable's declared type. – phoog Sep 17 '12 at 15:53
2
  1. Negligible if any. The return type would otherwise be compile checked. You shouldn't base decisions on it, anyhow.
  2. As many as you want as long as they are distinguishable.
  3. Static constructors are part of the type definition. They are invoked when the type is first referenced.
  4. What message are you receiving? R# is configurable.

Edit: (You can't beat the Skeet).

Tormod
  • 4,551
  • 2
  • 28
  • 50
2
  1. yes, there is some extra work required, but it is possible to use var keyword only in those situations in which it is pretty easy for the compiler to infer the type.

  2. There is no constraint on number of constructors, but there are some rules constructors have to follow (ie: it needs to be clear for the compiler which constructor to call)

  3. I can't telly you why - let's say this is just one of the rules. The interesting thing is beforefieldinit (http://stackoverflow.com/questions/610818/what-does-beforefieldinit-flag-do, http://csharpindepth.com/Articles/General/Beforefieldinit.aspx)

  4. I personally think that in this case it is just a matter of taste. Some people tend to use var as much as they can, while others do the opposite. I try to use when:

    • I am working with collections (or it takes a lot of text to tell the compiler about the type: instead of:
Dictionary<<OneOfMyClasses, OtherClasss> dictionary = new Dictionary<OneOfMyClasses, OtherClass>();

I tend to use var:

var dictionary = new Dictionary<OneOfMyClasses, OtherClass>();

Please mind that it doesn't affect readability of the code (i.e. it is still easy to understand what is actually happening).

Maciek Talaska
  • 1,628
  • 1
  • 14
  • 22
0

Thanks Everyone. After some time spent on research, I would like to add some points that might help someone.

Disclaimer:(The following points were derived(or even pasted) from codeproject and other such websites.

1) Every single class can have only one static constructor.

Reason: Static constructor must be parameter-less or simply, constructor overloading is not permitted. And since CLR is going to call this constructor, we do not have any control over passing values to this function. As we directly can’t call static constructors, there is no point in having multiple static constructors.

class Test
{
   static Test() {...}
   static Test(int a) {...} //would throw error as "Static constructor must be parameter less"
}

2) Static constructor should be declared without any access specifier.

Reason: Again CLR is going to call the static constructor not any object of the class. Hence, we donot need any access-specifier.

3) Static constructor must operate only on static variables of that class

Reason: Non-static members are specific to the object instance. There is no point in modifying a variable whose value depend/bind to their specific object instance.

4) Why should I use a static constructor ? Give me one good example

Reason: You can use a static constructor, say when you want to log the operations that you are going to perform using that class. MSDN says "A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file".

5) When exactly a static constructor is called ?

Answer: The user has no control on when the static constructor is executed in the program. .As others and MSDN points out "A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced."

6)When using base class and derived class in C#, when a new instance of a derived class is created, does base class constructor is called first or derived class constructor is called first?

Answer: The base class constructor is called first and then the derived class constructor.

Code example

class DerivedClass : ParentClass
{
     public DerivedClass()
     {
         Console.WriteLine("Derived class constructor!");
     }

}

 class ParentClass
{
     public ParentClass()
     {
         System.Console.WriteLine("Parent class constructor!");
     }
}

class Program
{
    static void Main(string[] args)
    {

        var a = new DerivedClass(); //Implicitly Typed local variables.

    }
}

7) Why in your above examples, both constructors have public access specifier ? What if I specify private or do-not specify access specifier at all?

Answer: When you do not specify access specifier(this case, the constructor automatically becomes private) or whenever you use a private access specifier, the class cannot be instantiated. Whenever a class contain one or more private constructors it strictly (!) cannot be instantiated. This type of constructors are called special instance constructor and is generally used when all the members of a class are static methods. (Probably the Math class should be a good example.)

**8)Bonus question on inheritance. Does a class inherit from two different classes ?

Strictly No. C# supports only direct inheritance and ofcourse you can use interfaces.For example,

    interface Test
   {
         void abc();
   }  
   class DerivedClass : ParentClass, Test //Test should not be a class. It can be  a interface.
{
     public DerivedClass()
     {
         Console.WriteLine("Derived class constructor!");
     }

     public void abc()
     {
          //should be publicly defined!
          //non public method could not implement from interface Test
     }

}

 class ParentClass
{
     public ParentClass()
     {
         System.Console.WriteLine("Parent class constructor!");
     }
}