Click here to Skip to main content
15,870,165 members
Please Sign up or sign in to vote.
5.00/5 (3 votes)
See more:
Hello,
I have a class which accepts more then 15 parameter in constructor and all parameters are used to assign value to it's own properties.

The problem is that, this class has become very static and in future if I want to intialise some more properties then I need to increase the number of parameter in constructor and do many changes in existing code.

How should I design this class so it can be easily extensible?

Thanks.
Maddie
Posted

Just an idea. Object and Collection Initializers[^]

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.
C#
public class Cat
{
    public int Age;
    public string Name;
}

Cat cat = new Cat { Age = 10, Name = "Fluffy" };


Instead of:
C#
public class Cat
{
    public int Age;
    public string Name;

    public Cat(int age, string name)
    {
      this.Age = age;
      this.Name = name;
    }
}

Cat cat = new Cat(10, "Fluffy");


If Cat.Age and Cat.Name is read only. Then change Age and Name to
C#
public readonly int Age;
public readonly string Name;


This way, you cannot change the value any more when. Only on create of a new Cat class.
 
Share this answer
 
v3
No need to do that at all. Just use the C# property initialization syntax.

C#
class Foo
{
    public int PropInt { get; set; }

    public string PropString { get; set; }
}

void Bar()
{
    Foo foo = new Foo()
    {
        PropInt = 10,
        PropString = "hello"
    };
}
 
Share this answer
 
v2
Comments
#realJSOP 10-May-11 9:47am    
5 - proposed as answer
Kim Togo 10-May-11 10:06am    
Good answer, my 5.
thatraja 10-May-11 13:54pm    
Fine answer.....
As an example of what Nish said, given the class below:

C#
public class MyClass
{
   public string Prop1 { get; set; }
   public string Prop2 { get; set; }
   public string Prop3 { get; set; }

   public MyClass()
   { 
      Prop1 = "";
      Prop2 = "";
      Prop3 = "";
   }
}


Call it like this:

C#
MyClass myClass = new MyClass();


or

C#
MyClass myClass = new MyClass(){Prop1="1"};


or

C#
MyClass myClass = new MyClass(){Prop1="1", Prop3="3"};

In the example above, any property you don't initialize will have the value "" (I don't believe in allowing uninitialized variables).

 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900