C# – Why do variables need a type

clanguagesvariables

So we write:

Customer c = new Customer();

Why is the design not such that we write:

c = new Customer();
c.CreditLimit = 1000;

The compiler can work out c points to a Customer and allow Customer's members to be invoked on c?

I know we may want to write:

IPerson c = new Customer();
IPerson e = new Employee();

so as to be able to write:

public string GetName(IPerson object)
{
    return object.Name
}

string name = GetName(c); // or GetName(e);

But if we wrote:

c = new Customer();
e = new Employee();

we could still write:

public string GetName(object)
{
    return object.Name
}    

string name = GetName(c); // or GetName(e);

The compiler could complain about the code immediately above if the type of object c references does not support a Name property (as it can check which members are used on the argument/parameter within the method), or the runtime could complain.

Even with C#'s dynamic keyword, we are still using a variable 'type' (determined at runtime). But why does a variable need a type at all? I am sure there must be a good reason, but I can't think of it!

Best Answer

But why does a variable need a type at all?

  1. This may catch bugs where an invalid, wrongly typed expression is assigned to a variable. Some languages have dynamic typing, which sacrifices the correctness guarantees of a type per variable for the kind of flexibility that you seem to desire.
  2. Types may allow the compiler to generate more efficient code. Dynamic typing means type checks have to be performed at runtime.