What is the difference between strong typing and weak typing in .NET?Strong typing
means that the type check is done at compile time and weak typing means
that the type check is done at run time. .NET languages incorporate strong
typing.
Every variable in .NET should have a type associated and the value assigned to the variable should match its type. If these rules are violated then compile time error will be displayed. This avoids abrupt error messages to be displayed to the User at run time. Consider the following example: public class
sampleClass { In this example, the variable sampleNo is not declared with any type. This will be detected by the compiler during compilation and you will get the following error: The name sampleNo does not exist in the current context Also, the
value assigned to the variable should be acceptable by the type. Consider
the following example: In this example,
note that the statement int sampleNo = 10 is legal because
you create a variable sampleNo, declare its type to Integer and define
its value to be 10, an integer value. But the next statement string
sampleStr=100 is incorrect because you create a variable called
sampleStr, declare its type to String and define its value to be 100,
an integer value instead of string value. Hence during compilation, you
will get the following error: However there
are situations when you cannot associate the actual type to a variable
at compile time itself. In such cases, you can declare the variable with
type var in C# version 3.0 or higher. Such variables can hold values of
any type and the actual type will be associated at run time.
|