Sorangwala Abbasali Sorangwala Abbasali - 1 year ago 132
C# Question

How to access a private constructor from controller to model class in mvc 4

Is there any way to access a private constructor from controller to model?

The controller containing method calling the model is as follows:

public ActionResult ReadXML()
XmlSerializer reader = new XmlSerializer(typeof(List<Asseted>));
TextReader textReader = new StreamReader(@"D:\Tial2.xml");
List<Asseted> asseted;
List<Asseted> list = new List<Asseted>();
asseted = (List<Asseted>)reader.Deserialize(textReader);
for (int i = 0; i < asseted.Count; i++)
string data123 = Convert.ToString(asseted[i].PopertyValue);
string data234 = Convert.ToString(asseted[i].PropertyName);
list.Add(new Asseted(data123,data234));

return View();

The model containing the Method to be called is as follows:

public class Asseted
string pName, pValue;
private string data234;
private string data123;

private Asseted(string data234, string data123)
// TODO: Complete member initialization
PropertyName = data234;
PopertyValue = data123;
public string PropertyName { get; set; }

public string PopertyValue { get; set; }

Answer Source

Is there any way to access a private constructor from controller to model?

While it may be arguable if this is the right way to solve your problem, the question itself can be answered with YES. And it's not even very hard with reflection.

ConstructorInfo constructor = typeof(Asseted).GetConstructor(
    BindingFlags.NonPublic | BindingFlags.Instance, 
    new[] { typeof(string), typeof(string) }, 

Asseted instance = constructor.Invoke(new[] { 
}) as Asseted;

Basically you get the type (Asseted), get the constructor that matches your known parameter types and invoke it. Done.

Additional Note: Depending on your compiler and actual code, you might run into a TypeAccessException.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download