简体   繁体   中英

How to force derived class to implement a property in C#

I have scenario like below

public abstract class Test 
{
   public string name; 
   public abstract bool is_selected();
}

public class Campus : Test 
{  

}

Now Campus must and should implement is_selected() method otherwise it throws an error. Adding to the same lines I want 'name' field also like that. I mean name field must be given a value.

How can I do that? Any help greatly appreciated.

Thanks in advance :)

I can find two options

  1. Use a parameterized constructor, so the derived class must provide a constructor which initialize the fields.
public abstract class Test 
{
   public string name;
   protected Test(string name){ this.name = name; }
}

public class Campus : Test 
{
   public Campus() : base("Init the name here") {}
}
  1. Use an abstract property, this is already metioned by other people.
public abstract class Test 
{
   public abstract string name { get; }
}

public class Campus : Test 
{  
   public override string name => "name";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM