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?
[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,
.. but I'm sure this opens up other problems I haven't thought of!
Obviously, if for some reason we wanted
exampleObjectto 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?