What do you think of using properties as object initializers in C#;

I was wondering what people thought of using properties as object initializers in C#. For some reason it seems to break the fundamentals of what constructors are used for.

An example...

public class Person
{
    string firstName;
    string lastName;

    public string FirstName
    {
      get { return firstName; }
      set { firstName = value; }
    }

    public string LastName
    {
      get { return lastName; }
      set { lastName= value; }
    }
}

Then doing object intialization with.....

Person p = new Person{ FirstName = "Joe", LastName = "Smith" };
Person p = new Person{ FirstName = "Joe" };

Answers


What you see here is some syntatic sugar provided by the compiler. Under the hood what it really does is something like:

Person p = new Person( FirstName = "Joe", LastName = "Smith" );

Person _p$1 = new Person();
_p$1.FirstName = "Joe";
_p$1.LastName = "Smith";
Person p = _p$1;

So IMHO you are not really breaking any constructor fundamentals but using a nice language artifact in order to ease readability and maintainability.


Object initializers does in no way replace constructors. The constructor defines the contract that you have to adhere to in order to create a instance of a class.

The main motivation for object initializers in the C# language is to support Anonymous Types.

var v = new { Foo = 1, Bar = "Hi" };
Console.WriteLine(v.Bar);

IMHO its sweet. Most objects are newed up with the default constructor, and must have some properties set before they are ready to run; so the object initializers make it easier to code against most objects out there.


Constructors should only really have arguments that are required to construct the object. Object initialisers are just a convenient way to assign values to properties. I use object initialisers whenever I can as I think it's a tidier syntax.


Since you're already using the new C# syntax, might as well use automatic properties as well, just to sweeten up your code a drop more:

instead of this:

string firstName;

public string FirstName
{
  get { return firstName; }
  set { firstName = value; }
}

use this:

public string FirstName { get; set; }

I think overall it is useful, especially when used with automatic properties. It can be confusing when properties are doing more than get/set. Hopefully this will lead to more methods, and reduce the abuse of properties.


Not your original question, but still...

Your class declaration can be written as:

public class Person
{
    public string FirstName { get; set; }
    public string LastName {get; set; }
}

and if it were my code, I'd probably have an object for Name with fields First and Last.


It's also quite necessary for projected classes returned from a language integrated query (linq)

var qry = from something in listofsomething
          select new {
                        Firstname = something.FirstName,
                        Lastname = something.Surname
                      }

Adding to Nescio's thoughts - I'd suggest in code reviews actively hunting down expensive transparent operations in property accessors e.g. DB round tripping.


Object Initializers help to reduce coding complexity in that you don't need to create a half dozen different constructors in order to provide initial values for properties. Anything that reduces redundant code is a positive, in my book.

I believe the primary reason the feature was added to the language is to support anonymous types for LINQ.


If you want to enforce the use of a constructor, you could set your object's default parameterless constructor to private, and leave public only some enforced constructors:

public class SomeObject
{
    private SomeObject()
    {}

    public SomeObject(string someString) //enforced constructor
    {}

    public string MyProperty { get; set; }
 }

Using the above definition, this throws an error:

var myObject = new SomeObject { MyProperty = "foo" } //no method accepts zero arguments for constructor

Of course this can't be done for all cases. Serialization, for example, requires that you have a non-private default constructor.


I for one am not happy with them. I don't think they have a place in the constructor, or MS should got back and refactor them to allow you to use them in a private fasion. If I construct an object I want to pass in some PRIVATE data. I want it set from the outside world once and that's it. With Object Initializers you allow the values passed into the constructor to be modifiable.

Maybe in the future they will change this.


Need Your Help

Delete item from listview and database

android sqlite listview android-listview

I'm trying to delete an item from a listview and from a sqlite database. There are several question on this site but I can't find a proper solution. My question is related with the design. I mean: ...

MVVMCross Android: value with binding not updated

c# android binding xamarin mvvmcross

I created simple app with Xamarin(Android)+Mvvmcross. I have property Data( type MyData) in my ViewModel.