3

In a C# block, I can define and initialize a variable as follows:

var xyz = new Xyz();

The type of xyz will be set accordingly.

However, at the class level, I have to specify the type twice:

class Abc
{
    Xyz xyz = new Xyz();
}

Is there a shorthand syntax that avoids typing out the type name twice?

This isn't such a big deal with short types like Xyz but a shorter notation would help with LongTypeNames.

dharmatech
  • 8,979
  • 8
  • 42
  • 88

2 Answers2

6

If you are using a few particular types and want them shortened you can create an alias with a using statement, eg:

using ShortName = Abc.Xyz.ClassWithAVeryLongNameThatYouDontLikeTypingTooOften;

then within that file you could do something like:

class Abc
{
    ShortName xyz = new ShortName();
}

But as far as I know there's no var equivalent at the class level.

joshuahealy
  • 3,529
  • 22
  • 29
3

This is a duplicate of this question: Using var outside of a method

Which contains a great in-depth answer: http://blogs.msdn.com/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx

Community
  • 1
  • 1
yamen
  • 15,390
  • 3
  • 42
  • 52