Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand notation for class member initialization [duplicate]

Tags:

c#

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.

like image 970
dharmatech Avatar asked Mar 09 '26 19:03

dharmatech


1 Answers

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.

like image 138
joshuahealy Avatar answered Mar 11 '26 09:03

joshuahealy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!