Prabhakaran Parthipan
Prabhakaran Parthipan

Reputation: 4273

How to initialize base class property from derived class?

I wrote Following code in my mvc Application.

public class TestController : Controller
{
    public ActionResult StronglyTypedView()
    {
      var obj = new MvcRouting.Models.Student();
      obj.age = 24;
      obj.name = "prab";
      ViewData.Model = obj;
      return View();
    }
}

In above code,ViewData is the property of ControllerBase class and Model is the property of ViewDataDictionary class.Same thing i tried in following code but i am getting null values in property1,how to solve this?

 public interface Iface1
 {       
    int age { get; set; }
 }
 public class classA : Iface1
 {       
   public int age { get; set; }
 }
 public abstract class classB
 {       
    public classA Property1 { get; set; }
 }
 public class TEST : classB
 {
   public void test()
   {          
      Property1.age = 24;
   }
   public static void Main()
   {
     TEST obj = new TEST();
     obj.test();
     Console.Read();
   }
 }

Upvotes: 1

Views: 1014

Answers (3)

Ronak Patel
Ronak Patel

Reputation: 2610

You forgot to initialize the Property1 before setting its property.

public class TEST : classB
{
   public void test()
   {    
      Property1 = new classA();
      Property1.age = 24;
   }
   public static void Main()
   {
     TEST obj = new TEST();
     obj.test();
     Console.Read();
   }
}

Upvotes: 0

Thilina H
Thilina H

Reputation: 5810

Use this instead.

public abstract class classB
{
 public classA Property1 { get; set; }

 public classB()
 {
   Property1 = new classA();
 }
}

Upvotes: 1

No Idea For Name
No Idea For Name

Reputation: 11607

you are getting null reference exception because you need to initialize Property1 in classB

 public interface Iface1
 {       
    int age { get; set; }
 }
 public class classA : Iface1
 {       
   public int age { get; set; }
 }
 public abstract class classB
 {       
    public classA Property1 { get; set; }
 }
 public class TEST : classB
 {
   public void test()
   {    
      if(Property1 == null)
      {
          Property1 = new classA();
      }

      Property1.age = 24;
   }
   public static void Main()
   {
     TEST obj = new TEST();
     obj.test();
     Console.Read();
   }
 }

Upvotes: 3

Related Questions