Search code examples
c#objectdry

Is there a DRYer way to initialise class values in C#?


Let's say I have a class:

class Foo
    {
        private int blah;
        private char bleh;
        private string bluh;
        //...
        public Foo()
        {
        }
    }

Now normally, I have to initialise it like this:

    public Foo(int blah, char bleh, string bluh,...)
    {
        this.blah=blah;
        this.bleh=bleh;
        this.bluh=bluh;
        //...
    }

This is dull and doesn't seem to follow the "Don't Repeat Yourself" principle so I'm looking for a better solution. Can this be done DRYer?

Edit: Changed variables to private to reflect a more common use case.


Solution

  • Use object initialization when initializing your variables/properties instead, if you really don't want to repeat yourself

    Like this

    Foo f = new foo{
        blah = 1;
        bleh = 'A';
        bluh = "something";
    };
    

    And also, don't use public accessor on your fields, that's not good.