Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to initialize a property at the point of declaration

Tags:

c#

c#-4.0

Imagine you have a field _items in a class. You can initialize it at the point of declaration:

class C
{
  IList<string> _items=new List<string>();
}

Now I want to convert this field to an auto generated property, but the initialization is now invalid:

class C
{
  public IList<string> Items=new List<string>(); {get; set;} // Invalid
}

So, I have to do:

class C
{
  public IList<string> Items {get; set;}

  public C
  {
    Items=new List<string>();
  }
}

But this is not nearly as convenient as initializing fields at the point of declaration. Is there a better way to do this, without having to (needlessly) back this property with a private (initialized at the point of declaration) field, for example.

Thanks

like image 884
Michael Goldshteyn Avatar asked Nov 01 '10 15:11

Michael Goldshteyn


People also ask

Which type of property is initialized when it is accessed first in Swift?

Classes, structures and enumerations once declared in Swift 4 are initialized for preparing instance of a class. Initial value is initialized for stored property and also for new instances too the values are initialized to proceed further. The keyword to create initialization function is carried out by 'init()' method.

When property is initialized in C#?

C# auto-initialize property is a feature, introduced in 6.0. It allows us to initialize properties without creating a constructor. Now, we can initialize properties along with declaration. In early versions, constructor is required to initialize properties.

Do you have to initialize variables in Swift?

Variables and constants do not require initialization when declared. However, the variable or constant requires type annotation so that when the compiler reads the code line-by-line, it can determine the data type at the time of the build. A Use of undeclared type error will be thrown otherwise.

When did the lazy property initialize?

lazy initialisation is a delegation of object creation when the first time that object will be called. The reference will be created but the object will not be created. The object will only be created when the first time that object will be accessed and every next time the same reference will be used.


2 Answers

No, automatic properties don't allow you to set an initial value.

It's annoying, but such is life. (It's annoying that they can't be readonly, too. But that's a rant for another day.)

EDIT: Both readonly automatically implemented properties and specifying an initial value are slated to be in C# 6.

like image 143
Jon Skeet Avatar answered Oct 09 '22 16:10

Jon Skeet


In c#6 you can write something like this:

class C
{
    public IList<string> Items {get; set;} = new List<string>();
}
like image 11
Martin Slezák Avatar answered Oct 09 '22 14:10

Martin Slezák