C# – using object initializers

Today something about simplifying your life.

 

While programming, there are so many situations when you want to write a simplier code. Maybe not in a “short code” project, but when you develop applications of 5000 – 6000 and more, you realize that you should write as best code as it is possible.

Since July, I have been working on a big project with other developers. There are so many situations in which I can’t read the code after two weeks, both if it is my code or other developer. In this post I want you to focus on object initializers.

 

Object initialization:

 

1. Using object initializer:

2. Using constructor to initialize:

 

 

3. Using accessors:

As you can see -> in the last example, class CSettings has a lot lines of code, and in my opinion it is the worst implementation. Of course sometimes you can’t use only the first option, but I wanted to show you how to write the best code in this situation.

 

MJ

3 thoughts on “C# – using object initializers

  1. Implementation of CSettings is “normal” 🙂
    Don’t worry about size. If you however want to make it “simplier” you can use auto properties
    public string Name {get;set;}

    1. Yes, of course it is possible. I don’t worry about size, but when you read code with initializers it is clearer than without it 😉

Zostaw komentarz

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s