Since some time I have been looking into languages and intend to understand the differences between them.
Please correct me if any information below is wrong. Thanks.
In languages such as PHP and JavaScript, there's no need to declare what type of data a variable will hold, so there are no constraints on the operators or methods you can use, for example:
// JavaScript code
var myvar = "Hello";
myvar += 1;
alert(myvar); // outputs "Hello1"
C# and VB.NET are strongly typed; however, they both offer a generic object type, for example:
// C# code
object myvar = "Hello";
myvar += 1;
Console.WriteLine(myvar);
This code will throw a compile-time error; In myvar can be set to anything( in object type we can store any type like (integer,string,float etc)But in this program compiler knows that myvar is a string at the point you try to add 1, so it leads to an error.
The dynamic type introduced in C# 4.0 is different:
// C# code
dynamic myvar = "Hello";
myvar += 1;
Console.WriteLine(myvar); // (output will be “Hello1”)
The compiler does not check the current state of a dynamic variable so no compile-time errors will occur. However, an exception will be thrown at runtime because 1 is unable to be added to a string.
Dynamic variables effectively inherit the properties and methods appropriate to their type at runtime.
Although dynamic variables offer flexibility, there are a number of risks:
1. No compile-time errors: a non-existent property or method could be used, such as myvar.DoesNotExist(). Your code would still compile and run, but an exception would be thrown when the call is attempted.Although dynamic variables offer flexibility, there are a number of risks:
No comments:
Post a Comment