I would like to set to variable result method from first class or second class which depend from type, what is wrong in my code??
public ActionResult Contact()
{
ViewBag.Message = GetValue(new ClassOne(), "classOne");
return View();
}
public string GetValue<T>(T customClass, string type)
{
if (type == "classOne") return customClass.ClassOneMethod();
else customClass.ClassTwoMethod();
}
class ClassOne
{
public string ClassOneMethod()
{
return "ClassOneMethod";
}
}
class ClassTwo
{
public string ClassTwoMethod()
{
return "ClassTwoMethod";
}
}
The problem is that the compiler knows nothing about type
Tat compile time and is unable to figure out that the object contained incustomClasshas a method calledClassOneMethodorClassTwoMethod. You have several options, for example deriving from a common base class overriding a virtual method or implementing an interface.Here some hints on how to do it using an interface. This is far from perfect but I tried to keep it quite close to your original code.