C# requires you to explicitly declare a variable, in addition to assigning it a value. This is done so that its clearer to both the compiler and the person reading the code that we're defining a new variable here, not using a previously-defined one, which can simplify parsing and make the code much clearer.
As you said, the statement ExampleClass c = new ExampleClass()
is simply a contraction of both these actions, which is why you feel the duplication - it's two different actions. But it does feel clunky. This is why the C# 3.0 specifications (in VS2008) added the var
keyword, which lets you skip a lot of the verbosity, even if it wasn't the primary motivation for the feature.
Using var
, our example code becomes var c = new ExampleClass()
- much easier to scan, but still explicitly declaring as well as assigning. It gets even more useful with long class names - var complexDictionary = new Dictionary<Tuple<int,int>, List<string>>()
, for instance. Imagine writing that twice!
Of course, var
was originally introduced to support anonymous types. These are used by lambda expressions and LINQ, and create types with names that are both clumsy (MyMethod<>Class5
, or similar) and also not known to the developer, so that saves us a lot of problems.
Additionally, in your edit, you proposed a similar but inverse solution to the duplication - to keep the declaration explicit, but the instantiation implicit. This saves about as many characters as var
, but is a lot less flexible. Consider that variable declaration is very simple - you simply state the type of your variable. Initialization, though, is more complex. Sometimes you simply use new
, and then we can use your new()
syntax. But often we have different constructor parameters. Or how about initializing using a factory method, like ExampleClass exampleObject = ExampleBuilder.CreateExample();
? Your syntax doesn't save us anything there, whereas the type inference in var
will allow us to use var exampleObject = ExampleBuilder.CreateExample();
smoothly.