Why is C# statically typed?

前端 未结 17 2770
不思量自难忘°
不思量自难忘° 2020-12-01 05:07

I am a PHP web programmer who is trying to learn C#.

I would like to know why C# requires me to specify the data type when creating a variable.

Class         


        
17条回答
  •  失恋的感觉
    2020-12-01 06:00

    Why do we need to know the data type before a class instance?

    You don't! Read from right to left. You create the variable and then you store it in a type safe variable so you know what type that variable is for later use.

    Consider the following snippet, it would be a nightmare to debug if you didn't receive the errors until runtime.

     void FunctionCalledVeryUnfrequently()
     {
       ClassA a = new ClassA();
       ClassB b = new ClassB();
       ClassA a2 = new ClassB(); //COMPILER ERROR(thank god)
    
       //100 lines of code
    
       DoStuffWithA(a);
       DoStuffWithA(b);      //COMPILER ERROR(thank god)
       DoStuffWithA(a2);
     }
    

    When you'r thinking you can replace the new Class() with a number or a string and the syntax will make much more sense. The following example might be a bit verbose but might help to understand why it's designed the way it is.

       string s = "abc";
       string s2 = new string(new char[]{'a', 'b', 'c'});
       //Does exactly the same thing
    
       DoStuffWithAString("abc");
       DoStuffWithAString(new string(new char[]{'a', 'b', 'c'}));
       //Does exactly the same thing
    

提交回复
热议问题