I have a partial class with no constructor code. I want to add constructor code but is it possible to add this constructor in another class which is a part of this partial class.
4 Answers
add this constructor in another class
No, you can't.
But in the same partial class or may be on a different file, yes
public partial class Test
{
}
public partial class Test
{
public Test()
{
}
}
3 Comments
partial to split implemetation between files.You can add a constructor to a partial class, if your class is partial to that class!
Here's an example of what you can do:
public partial class Test
{
public string Name { get; set; }
public Test(string name, int age)
{
Name = name;
Age = age;
}
}
public partial class Test
{
public int Age { get; set; }
public Test(string name)
{
Name = name;
}
}
Essentially this would be the same as doing:
public class Test
{
public int Age { get; set; }
public string Name { get; set; }
public Test(string name)
{
Name = name;
}
public Test(string name, int age)
{
Name = name;
Age = age;
}
}
1 Comment
If i understand the question correctly, the answer is that you can add the constructor in any side of the partial class you wish. But you cant add it in a nested class that exists in your partial class, as that is a totally different class. Examples are provided on the official msdn site that make it clear.
public partial class <yourclass>and make sure you specify the same namespace as in generated class