-5

I have this use case:

using System;
namespace ConsoleApplication11
{
  using System.Collections.ObjectModel;

  public class Program
  {
    static void Main(string[] args)
    {
      var test2 = "Name";
      string test1 = "Name";
      String test3 = "Name";

     Console.WriteLine(test1 + test2 + test3 + "NameNotDefined");
   }
 }
}

What will do the compiler:

  • in this line Console.WriteLine(test1 + test2 + test3 + "Alugili");?
  • with the last one "NameNotDefined"?

Did the compiler call ToString() to each of them and than apply the + Operator?

Any body can please explain to me the difference between the var and String and string and "" and how the complier will interact with them?

Bassam Alugili
  • 13,927
  • 7
  • 49
  • 67

2 Answers2

1

All three compile identically in C#. The "var" keyword is used to infer the type at compile-time, and the compiler infers that you're using a string (which is the same thing as String).

Dave Markle
  • 88,065
  • 20
  • 140
  • 165
1

string is an alias for System.String, both of them compile to the same code, so at execution time there is no difference.

The + is used for string concatenation, so when you write test1 + test2 + test3 + "Alugili" it concatenates all of the strings and form one string. In .net string's are immutable i.e. strings cannot be altered. When you alter a string, you are actually creating a new string.

About var MSDN says this :

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

Sayse
  • 38,955
  • 14
  • 69
  • 129
Bibhu
  • 3,943
  • 4
  • 29
  • 61
  • So in the last one "Alugili" a new object of type string will be created and injected to code you mean that? – Bassam Alugili Sep 11 '13 at 13:15
  • 1
    @Bassam Alugili - Yes, for more info check out this MSDN link http://msdn.microsoft.com/en-us/library/ms228362%28v=vs.90%29.aspx – Bibhu Sep 11 '13 at 13:24