Why is C# statically typed?

2020-01-28 03:12发布

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 classInstance = new Class();

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

17条回答
The star\"
2楼-- · 2020-01-28 03:42

Ultimately because Anders Hejlsberg said so...

查看更多
Root(大扎)
3楼-- · 2020-01-28 03:44

C# is a statically-typed, strongly-typed language like C or C++. In these languages all variables must be declared to be of a specific type.

查看更多
男人必须洒脱
4楼-- · 2020-01-28 03:44

That's the difference between a strongly typed and weakly typed language. C# (and C, C++, Java, most more powerful languages) are strongly typed so you must declare the variable type.

查看更多
Emotional °昔
5楼-- · 2020-01-28 03:44

In C# 3.0, you can use the 'var' keyword - this uses static type inference to work out what the type of the variable is at compile time

var foo = new ClassName();

variable 'foo' will be of type 'ClassName' from then on.

查看更多
够拽才男人
6楼-- · 2020-01-28 03:44

Static typing also allows the compiler to make better optimizations, and skip certain steps. Take overloading for example, where you have multiple methods or operators with the same name differing only by their arguments. With a dynamic language, the runtime would need to grade each version in order to determine which is the best match. With a static language like this, the final code simply points directly to the appropriate overload.

Static typing also aids in code maintenance and refactoring. My favorite example being the Rename feature of many higher-end IDEs. Thanks to static typing, the IDE can find with certainty every occurrence of the identifier in your code, and leave unrelated identifiers with the same name intact.

I didn't notice if it were mentioned yet or not, but C# 4.0 introduces dynamic checking VIA the dynamic keyword. Though I'm sure you'd want to avoid it when it's not necessary.

查看更多
成全新的幸福
7楼-- · 2020-01-28 03:44

Statically typed means that Compiler can perform some sort of checks at Compile time not at run time. Every variable is of particular or strong type in Static type. C# is strongly definitely strongly typed.

查看更多
登录 后发表回答