0

I'm working on ASP.NET MVC3 with C#. I got an error like below

Type 'Test' already defines a member called 'Test' with the same parameter types

My Code is:

public partial class Test
{
    Test()
    {
       //some code
    }
}

public partial class Test
{
    Test()
    {
        days = new List<SelectListItem>();
    }

    public IList<SelectListItem> days { get; set; }
}

Both Classes are in different files.
I don't want to modify first partial class. So How can I handle this type of situation where I've to call same constructor twice?

Krutal Modi
  • 477
  • 9
  • 25

2 Answers2

7

One approach is partial methods:

public partial class Test
{
    partial void OnCtor() // implement the partial method
    {
       //some code
    }
}

public partial class Test
{
    partial void OnCtor(); // declare the partial method
    Test()
    {
        days = new List<SelectListItem>();
        OnCtor();          // invoke the partial method **if implemented**
    }

    public IList<SelectListItem> days { get; set; }
}

The key thing: if you don't add an OnCtor method somewhere with an implementation, then it completely evaporates from the calling code, i.e. the call is not compiled.

This is a common approach in code-generators, as it allows the generated code to publish and advertise extension points, which the developer can then customise in their own part of the partial class, but with zero impact (performance etc) if they are not implemented.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
5

I'd solve it by getting rid of an unnecessary constructor:

public partial class Test
{
    Test()
    {
       //some code
    }
}

public partial class Test
{
    private IList<SelectListItem> _days = new List<SelectListItem>();

    public IList<SelectListItem> days {
        get { return _days; }
        set { _days = value; }
    }
}