When learning C# (and OO concepts more generally at the same time) something I found very distracting is exemplified by the following line:
ExampleClass exampleObject = new ExampleClass();
It's the apparent redundant repetition that bothered me. Some light dawned when I grasped the difference between declaring a variable and assigning it a value or reference (and that these processes can be separate). However, the above usage is extremely common.
Obviously, I've learnt to live with it (and am not expecting the C# syntax to change!) but I wondered if there is a better way. Would there be any merit in the following:
exampleObject = new ExampleClass();
Where the variable exampleObject
is strongly typed as ExampleClass
when it is not specified?
EDIT
[after commenters pointed out ambiguity of above between a declaration of a new, and an assignment, of an existing, variable:]
An alternative hypothetical shortened syntax, which avoids the declaration/assignment ambiguity, is:
ExampleClass exampleObject = new();
...where this would create a new instance of ExampleClass
, the type having been specified in the declaration of its referencing variable, exampleObject
.
.. but I'm sure this opens up other problems I haven't thought of!
/EDIT
Obviously, if for some reason we wanted exampleObject
to be of type Object
, or - a more common requirement - to be of the type of a parent class of ExampleClass
, we would specify these types in front of the variable name in the standard way, but is there any drawback to my suggested shorthand in this very common scenario?
var
for (admittedly, quite limited) type inference:var exampleObject = new ExampleClass();
.var
on fields. Eric Lippert explains why. And obviously, you can't make a declaration without a type and without a var because then there's no way to differentiate between a declaration and an assignment.