Using an overridden property in base class - c#

I have the following:
class Info
{
public string str;
};
class CarInfo : Info {}
class InfoContainer
{
public virtual List<Info> info_list {get; set;}
public bool is_known(Info inf)
{
if (-1 == info_list.FindIndex( i => i.str == inf.str) return false;
return true;
}
}
class CarFleetInfo : InfoContainer
{
new public List<CarInfo> info_list;
CarFleetInfo()
{
info_list = new List<CarInfo>();
}
}
Main()
{
CarInfo c = new CarInfo();
Info i = new Info();
c.is_known(i);
}
I have few other "specific info" class that inherited from Info (like CarInfo ), and few classes that inherited from InfoContainer, which are each overrides info_list with other a list of object of some "specific info".
now, the call to c.is_known(i) raise an exception saying info_list is null.

Your problem is the new keyword on new public List<CarInfo> info_list;. In this context, new means "Ignore the definition provided by my base class (if any), and use my own definition instead". So when you set a CarInfo's info_list, you're not setting the base Info's info_list. Then when you try to access the info_list that's part of an Info, it's null.
The best way to fix it is simply to take out the CarInfo's info_list and simply use the base class's version. This is the correct way to do what you're trying to do here, although there are others that could be used.

You aren't overriding the info_list property, you are shadowing it.
To override the property you should use the override keyword instead of the new keyword, and then the code will work as intended.
When you shadow the property the subclass gets it's own property with the same name, that the base class doesn't know anything about.

You're using new on a property which explicitly hides the member from its base class. It would be invalid to use override since a List<Info> is not a List<CarInfo>.
Instead consider using generics:
class Info
{
public string Foo { get; set; }
}
class CarInfo : Info {}
class InfoContainer<T>
where T: Info
{
public List<T> info_list { get; set; }
public bool is_known(T inf)
{
if (-1 == info_list.FindIndex(i => i.Foo == inf.Foo)) return false;
return true;
}
}
class CarFleetInfo : InfoContainer<CarInfo>
{
}

There are two problems:
You should be overriding instead of shadowing
You cannot override a method with a different signature
class Info
{
public string str;
};
class CarInfo : Info {}
class InfoContainer
{
public virtual List<Info> info_list {get; set;}
public bool is_known(Info inf)
{
if (!info_list.Exists(p => p.str == inf.str)) return false;
return true;
}
}
class CarFleetInfo : InfoContainer
{
public override List<Info> info_list { get; set; }
CarFleetInfo()
{
info_list = new List<Info>();
}
}
You cannot have public List<CarInfo> override public List<Info>

I think you can't assign a List<CarInfo> to a List<Info>, so you can't override the info_list that way. To work around, you have to use generic class instead defined as follow:
class InfoContainer<T> where T : Info
{
public virtual List<T> info_list {get; set;}
public bool is_known(T inf)
{
if (-1 == info_list.FindIndex( i => i.str == inf.str) return false;
return true;
}
}
class CarFleetInfo<T> : InfoContainer<T> where T : CarInfo
{
public override List<T> info_list {get;set;}
public CarFleetInfo(){
info_list = new List<T>();
}
}

The purpose of a base class is to provide functions and definitions that will be overridden. Overriding a base class is meaningless. May be a good exercise on breaking a language, but in general you're creating a paradox and an infinite loop within your compiler. The override attribute means to the preprocessor that your code should run priority rather than it's base class operation.
However, you should still call the base class operation in most cases to ensure all fields and objects of the inherited object are instantiated and correctly initialized.

Related

Casting to a generic interface [duplicate]

I have the following classes
public abstract class BaseViewPresenter { }
public abstract class BaseView<T> : UserControl
where T : BaseViewPresenter { }
public class LoginPresenter : BaseViewPresenter { }
public partial class LoginView : BaseView<LoginPresenter> { }
I have a method that looks like this (simplified)
public BaseView<BaseViewPresenter> Resolve(BaseViewPresenter model)
{
var type = model.GetType();
var viewType = _dataTemplates[type];
// Correctly creates BaseView object
var control = Activator.CreateInstance(viewType);
// Fails to cast as BaseView<BaseViewPresenter> so returns null
return control as BaseView<BaseViewPresenter>;
}
When I call this using an instances of LoginPresenter
var login = new LoginPresenter();
var ctl = Resolve(login);
The line Activator.CreateInstance(viewType) correctly resolves into a new instances of my LoginView, however control as BaseView<BaseViewPresenter> can't do the cast correctly so returns null.
Is there a way to correctly cast the control into BaseView<BaseViewPresenter> without using specific type generics?
Since LoginView inherits from BaseView<LoginPresenter>, and LoginPresenter inherits from BaseViewPresenter, I would assume there's a way to convert LoginView to BaseView<BaseViewPresenter>.
I am stuck with using .Net 3.5
This is a very frequently asked question. Let's rename your types:
abstract class Fruit { } // was BaseViewPresenter
abstract class FruitBowl<T> where T : Fruit // was BaseView
class Apple : Fruit { } // was LoginPresenter
class BowlOfApples : FruitBowl<Apple> { } // was LoginView
Your question now is:
I have a BowlOfApples, which inherits from FruitBowl<Apple>. Why can I not use it as a FruitBowl<Fruit>? An apple is a fruit, so a bowl of apples is a bowl of fruit.
No, it isn't. You can put a banana in a bowl of fruit, but you can't put a banana in a bowl of apples, and therefore a bowl of apples is not a bowl of fruit. (And by similar argument, a bowl of fruit is not a bowl of apples either.) Since the operations you can legally perform on the two types are different, they cannot be compatible.
Here is a photo of StackOverflow legend Jon Skeet demonstrating this fact:
The feature you want is called generic contravariance, and it is supported only on interfaces and delegate types when the compiler can prove that the variance is safe, and when the varying type is a reference type. For example, you can use an IEnumerable<Apple> in a context where IEnumerable<Fruit> is needed because the compiler can verify that there is no way that you can put a Banana into a sequence of fruit.
Do a search on "C# covariance and contravariance" on this site or on the web and you'll find many more details about how this feature works. In particular, my series of articles on how we designed and implemented this feature in C# 4 starts here: http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx
I accepted Eric's answer since it provides a great explanation of why what I wanted wasn't possible, but I also thought I'd share my solution in case anyone else runs into this same problem.
I removed the generic type parameter from my original BaseView class, and created a 2nd version of the BaseView class that included the generic type parameter and specifics for it.
The first version is used by my .Resolve() method or other code that doesn't care about the specific types, and the second version is used by any code that does care, such as the implentation of a BaseView
Here's an example of how my code ended up looking
// base classes
public abstract class BaseViewPresenter { }
public abstract class BaseView : UserControl
{
public BaseViewPresenter Presenter { get; set; }
}
public abstract class BaseView<T> : BaseView
where T : BaseViewPresenter
{
public new T Presenter
{
get { return base.Presenter as T; }
set { base.Presenter = value; }
}
}
// specific classes
public class LoginPresenter : BaseViewPresenter { }
public partial class LoginView : BaseView<LoginPresenter>
{
// Can now call things like Presenter.LoginPresenterMethod()
}
// updated .Resolve method used for obtaining UI object
public BaseView Resolve(BaseViewPresenter presenter)
{
var type = model.GetType();
var viewType = _dataTemplates[type];
BaseView view = Activator.CreateInstance(viewType) as BaseView;
view.Presenter = presenter;
return view;
}
You're expecting to treat the type as being covariant with respect to the generic argument. Classes can never be covariant; you'd need to use an interface rather than (or in addition to) an abstract class to make it covariant with respect to T. You'd also need to be using C# 4.0.
My usual solution to this problem is to create an intermediary class that has access to the type-parametric class's methods through delegates. Fields can also be accessed through getters/setters.
The general pattern goes:
public abstract class Super {}
public abstract class MyAbstractType<T> where T : Super {
public MyGeneralType AsGeneralType() {
return MyGeneralType.Create(this);
}
// Depending on the context, an implicit cast operator might make things
// look nicer, though it might be too subtle to some tastes.
public static implicit operator MyGeneralType(MyAbstractType<T> t) {
return MyGeneralType.Create(t);
}
public int field;
public void MyMethod1() {}
public void MyMethod2(int argument) {}
public abstract bool MyMethod3(string argument);
}
public delegate T Getter<T>();
public delegate void Setter<T>(T value);
public delegate void MyMethod1Del();
public delegate void MyMethod2Del(int argument);
public delegate bool MyMethod3Del(string argument);
public class MyGeneralType {
public Getter<int> FieldGetter;
public Setter<int> FieldSetter;
public MyMethod1Del MyMethod1;
public MyMethod2Del MyMethod2;
public MyMethod3Del MyMethod3;
public static MyGeneralType Create<T>(MyAbstractType<T> t) where T : Super {
var g = new MyGeneralType();
g.FieldGetter = delegate { return t.field; };
g.FieldSetter = value => { t.field = value; };
g.MyMethod1 = t.MyMethod1;
g.MyMethod2 = t.MyMethod2;
g.MyMethod3 = t.MyMethod3;
return g;
}
public int field {
get { return FieldGetter(); }
set { FieldSetter(value); }
}
}
The above exemplifies getting all the methods and fields but normally I only need a few of them. This is a general solution to the problem and one could feasibly write a tool to generate these intermediary classes automatically, which I might at some point.
Try it here: https://dotnetfiddle.net/tLkmgR
Note that this is enough for all my cases, but you can be extra hacky with this:
public abstract class MyAbstractType<T> where T : Super {
// ... Same everything else ...
// data fields must become abstract getters/setters, unfortunate
public abstract int field {
get;
set;
}
public static implicit operator MyAbstractType<Super>(MyAbstractType<T> t) {
return MyGeneralType.Create(t);
}
}
public class MyGeneralType : MyAbstractType<Super> {
// ... same constructors and setter/getter
// fields but only keep method fields
// that contain the method references for
// implementations of abstract classes,
// and rename them not to clash with the
// actual method names ...
public MyMethod3Del myMethod3Ref;
// Implement abstract methods by calling the corresponding
// method references.
public override bool MyMethod3(string argument) {
return myMethod3Ref(argument);
}
// Same getters/setters but with override keyword
public override int field {
get { return FieldGetter(); }
set { FieldSetter(value); }
}
}
And there you go, now you can literally cast a MyAbstractType<Sub> where Sub : Super to a MyAbstractType<Super>, although it's no longer the same object anymore, but it does retain the same methods and data, it's sort of a complex pointer.
public class Sub : Super {}
public class MySubType : MyAbstractType<Sub> {
public int _field;
public override int field {
get { return _field; }
set { _field = value; }
}
public override bool MyMethod3(string argument) {
Console.WriteLine("hello " + argument);
return argument == "world";
}
}
public class MainClass {
public static void Main() {
MyAbstractType<Sub> sub = new MyAbstractType<Sub>();
MyAbstractType<Super> super = sub;
super.MyMethod3("hello"); // calls sub.MyMethod3();
super.field = 10; // sets sub.field
}
}
This isn't as good in my opinion, the other version of MyGeneralType is a more straighforward layer over the concrete types, plus it doesn't require rewriting the data fields, but it does actually answer the question, technically. Try it here: https://dotnetfiddle.net/S3r3ke
Example
Using these abstract classes:
public abstract class Animal {
public string name;
public Animal(string name) {
this.name = name;
}
public abstract string Sound();
}
public abstract class AnimalHouse<T> where T : Animal {
List<T> animals;
public AnimalHouse(T[] animals) {
this.animals = animals.ToList();
}
public static implicit operator GeneralAnimalHouse(AnimalHouse<T> house) {
return GeneralAnimalHouse.Create(house);
}
public List<string> HouseSounds() {
return animals.Select(animal => animal.Sound()).ToList();
}
}
We make this "general" variant:
public delegate List<string> HouseSoundsDel();
public class GeneralAnimalHouse {
public HouseSoundsDel HouseSounds;
public static GeneralAnimalHouse Create<T>(AnimalHouse<T> house) where T : Animal {
var general = new GeneralAnimalHouse();
general.HouseSounds = house.HouseSounds;
return general;
}
}
And finally with these inheritors:
public class Dog : Animal {
public Dog(string name) : base(name) {}
public override string Sound() {
return name + ": woof";
}
}
public class Cat : Animal {
public Cat(string name) : base(name) {}
public override string Sound() {
return name + ": meow";
}
}
public class DogHouse : AnimalHouse<Dog> {
public DogHouse(params Dog[] dogs) : base(dogs) {}
}
public class CatHouse : AnimalHouse<Cat> {
public CatHouse(params Cat[] cats) : base(cats) {}
}
We use it like this:
public class AnimalCity {
List<GeneralAnimalHouse> houses;
public AnimalCity(params GeneralAnimalHouse[] houses) {
this.houses = houses.ToList();
}
public List<string> CitySounds() {
var random = new Random();
return houses.SelectMany(house => house.HouseSounds())
.OrderBy(x => random.Next())
.ToList();
}
}
public class MainClass {
public static void Main() {
var fluffy = new Cat("Fluffy");
var miu = new Cat("Miu");
var snuffles = new Cat("Snuffles");
var snoopy = new Dog("Snoopy");
var marley = new Dog("Marley");
var megan = new Dog("Megan");
var catHouse = new CatHouse(fluffy, miu, snuffles);
var dogHouse = new DogHouse(snoopy, marley, megan);
var animalCity = new AnimalCity(catHouse, dogHouse);
foreach (var sound in animalCity.CitySounds()) {
Console.WriteLine(sound);
}
}
}
Output:
Miu: meow
Snoopy: woof
Snuffles: meow
Fluffy: meow
Marley: woof
Megan: woof
Notes:
I added names so it's clear that the method references carry their owner's data with them, for those unfamiliar with delegates.
The required using statements for this code are System, System.Collections.Generic, and System.Linq.
You can try it here: https://dotnetfiddle.net/6qkHL3#
A version that makes GeneralAnimalHouse a subclass of AnimalHouse<Animal> can be found here: https://dotnetfiddle.net/XS0ljg

How to correctly override and enhance property

Code tells more than words, so look at this:
public abstract class ViewObject: INotifyPropertyChanged {
public virtual string Id {
get {
return this.GetType().Name;
}
}
}
public class Object : ViewObject {
private string id = string.Empty;
public override string Id {
get {
return this.id;
}
set {
this.id = value;
}
}
}
What is the correct way to implement the desired behaviour of a base implementation in the abstract class (yes, it should have a base implementation for this, but not for other things)?
I can only think of using the new keywork instead of override to simply hide the base implementation, but is this right?
you are already using inheritance. Override method is useful when method name and parameter is same.
here you can use method overloading.
for method overload name is same but parameter is different. you can use in inheritance also.
i hope this is useful
If you use the new keyword and someone casts your derived object to the base class, the base implementation will be called and not the derived one. To avoid this, the override is needed.
But that is currently not possible, cause your base class doesn't support a setter. So stick to the override and implement a set method in the base class that simply throws a NotSupportedExecption.
public abstract class ViewObject
{
public virtual string Id
{
get { return this.GetType().Name; }
set { throw new NotSupportedException(); }
}
}
public class Object : ViewObject
{
private string id = string.Empty;
public override string Id
{
get { return this.id; }
set { this.id = value; }
}
}

Abstract factory method with fixed type parameter

Is there a neat way to specify that a class must contain a factory method that returns the same kind of object as the class that overrides the abstract method? (Edit: Or as Johnathon Sullinger more eloquently puts it, [...] have a base class enforce a child class to implement a method that returns an instance of the child class itself, and not allow returning an instance of any other Type that inherits from the base class.)
For example, if I've got two classes, SimpleFoo : BaseFoo and FancyFoo : BaseFoo, can I define an abstract factory method public TFoo WithSomeProp(SomeProp prop) where TFoo is a type parameter that is somehow fixed by the abstract method definition to the particular class that overrides it?
I had hopes of compile-time guarantees that either
a concrete WithSomeProp method definition in SomeFoo : BaseFoo will only be able to produce SomeFoos. If static abstract method definitions were legal, perhaps the following (pseudo-syntax) method extension best expresses this need:
public static abstract TFoo WithSomeProp<TFoo>(this TFoo source, SomeProp prop)
where TFoo : BaseFoo;
I don't think this is possible in C#.
or at least some way to parameterize the return type in an abstract method, e.g.
public abstract TFoo WithSomeProp<TFoo>(SomeProp prop)
where TFoo : BaseFoo;
This wouldn't prevent FancyFoo.WithSomeProp from returning SimpleFoos, but ok.
This abstract method itself seems to work, but my concrete definition then fails:
public override SimpleFoo WithSomeProp(SomeProp prop)
{
return new SimpleFoo(this.SomeOtherProp, ..., prop);
}
with the warning
no suitable method found to override
It appears to me that specifying type parameters in an abstract method does not allow fixing them in the overrides of those definitions, but rather it specifies that "A method with a type parameter should exist".
For now I simply have public abstract BaseFoo WithSomeProp(SomeProp prop);.
It sounds like what you want to do, is have a base class enforce a child class to implement a method that returns an instance of the child class itself, and not allow returning an instance of any other Type that inherits from the base class. Unfortunately, to the best of my knowledge, that is not something you can do.
You can however force the child-class to specify what it's Type is to the base class, so that the base class can then enforce that the return value must be the Type specified by the child-class.
For instance, given a base class called BaseFactory, and BaseFactory<T>, we can create an abstract class that requires children to specify to the parent, what type the creation method returns. We include a BaseFactory class so we can constrain T to only being children classes of BaseFactory.
EDIT
I'll leave the original answer below in the event that it helps, but after some thought, I think I've got a better solution for you.
You'll still need the base class to take a generic argument that defines what the child Type is. The difference now however is that the base class has a static creation method instead of instance methods. You can use this creation method to create a new instance of the child class, and optionally invoke a callback for configuring the property values on the new instance before you return it.
public abstract class BaseFactory { }
public abstract class BaseFactory<TImpl> : BaseFactory where TImpl : BaseFactory, new()
{
public static TImpl Create(Action<TImpl> itemConfiguration = null)
{
var child = new TImpl();
itemConfiguration?.Invoke(child);
return child;
}
}
You then just create your children classes normally, without worrying about overriding any methods.
public class Foo : BaseFactory<Foo>
{
public bool IsCompleted { get; set; }
public int Percentage { get; set; }
public string Data { get; set; }
}
public class Bar : BaseFactory<Bar>
{
public string Username { get; set; }
}
Then you would use the factory as-such.
class Program
{
static void Main(string[] args)
{
// Both work
Bar bar1 = Bar.Create();
Foo foo1 = Foo.Create();
// Won't compile because of different Types.
Bar bar2 = Foo.Create();
// Allows for configuring the properties
Bar bar3 = Bar.Create(instanceBar => instanceBar.Username = "Jane Done");
Foo foo2 = Foo.Create(instanceFoo =>
{
instanceFoo.IsCompleted = true;
instanceFoo.Percentage = 100;
instanceFoo.Data = "My work here is done.";
});
}
Original Answer
The BaseFactory<T> will be reponsible for creating a new instance of TImpl and giving it back.
public abstract class BaseFactory { }
public abstract class BaseFactory<TImpl> : BaseFactory where TImpl : BaseFactory
{
public abstract TImpl WithSomeProp();
}
Now, your child class can be created, and inherit from BaseFactory<T>, telling the base class that T represents itself. This means the child can only ever return itself.
public class Foo : BaseFactory<Foo>
{
public override Foo WithSomeProp()
{
return new Foo();
}
}
public class Bar : BaseFactory<Bar>
{
public override Bar WithSomeProp()
{
return new Bar();
}
}
Then you would use it like:
class Program
{
static void Main(string[] args)
{
var obj1 = new Bar();
// Works
Bar obj2 = obj1.WithSomeProp();
// Won't compile because obj1 returns Bar.
Foo obj3 = obj1.WithSomeProp();
}
}
If you really want to make sure that the generic specified is the same as the owning Type, you could instead make WithSomeProp a protected method, so that children classes can only see it. Then, you create a public method on the base class that can do type checking.
public abstract class BaseFactory { }
public abstract class BaseFactory<TImpl> : BaseFactory where TImpl : BaseFactory
{
protected abstract TImpl WithSomeProp();
public TImpl Create()
{
Type myType = this.GetType();
if (typeof(TImpl) != myType)
{
throw new InvalidOperationException($"{myType.Name} can not create instances of itself because the generic argument it provided to the factory is of a different Type.");
}
return this.WithSomeProp();
}
}
public class Foo : BaseFactory<Foo>
{
protected override Foo WithSomeProp()
{
return new Foo();
}
}
public class Bar : BaseFactory<Bar>
{
protected override Bar WithSomeProp()
{
return new Bar();
}
}
class Program
{
static void Main(string[] args)
{
var obj1 = new Bar();
// Works
Bar obj2 = obj1.Create();
// Won't compile because obj1 returns Bar.
Foo obj3 = obj1.Create();
}
}
Now, if you create a child class that passes a different Type as T, the base class will catch it and throw an exception.
// Throws exception when BaseFactory.Create() is called, even though this compiles fine.
public class Bar : BaseFactory<Foo>
{
protected override Foo WithSomeProp()
{
return new Foo();
}
}
Not sure if this gets you what you wanted at least, but I think this will probably be the closest thing you can get.
Inspired by Johnathon Sullinger's fine answer, here is the code I ended with. (I added a theme.)
I passed the type parameter T along with the class definition and constrained that T : Base<T>.
BaseHyperLink.cs:
public abstract class BaseHyperLink<THyperLink> : Entity<int>
where THyperLink : BaseHyperLink<THyperLink>
{
protected BaseHyperLink(int? id, Uri hyperLink, ContentType contentType, DocumentType documentType)
: base(id)
{
this.HyperLink = hyperLink;
this.ContentType = contentType;
this.DocumentType = documentType;
}
public Uri HyperLink { get; }
public ContentType ContentType { get; }
public DocumentType DocumentType { get; }
public abstract THyperLink WithContentType(ContentType contentType);
}
SharedHyperLink.cs:
public sealed class SharedHyperLink : BaseHyperLink<SharedHyperLink>
{
public SharedHyperLink(int? id, Uri hyperLink, ContentType contentType, DocumentType documentType)
: base(id, hyperLink, contentType, documentType)
{
}
public override SharedHyperLink WithContentType(ContentType contentType)
{
return new SharedHyperLink(this.Id, contentType, this.DocumentType);
}
}
MarkedHyperLink.cs:
public sealed class MarkedHyperLink : BaseHyperLink<MarkedHyperLink>
{
public MarkedHyperLink(int? id, Uri hyperLink, ContentType contentType, DocumentType documentType, Mark mark)
: base(id, hyperLink, contentType, documentType)
{
this.Mark = mark;
}
public Mark Mark { get; }
public override MarkedHyperLink WithContentType(ContentType contentType)
{
return new MarkedHyperLink(this.Id, contentType, this.DocumentType, this.Mark);
}
}

How to use a derived property on a base class?

I have a base class that has a property and a method that uses that property. I have a class that inherits that base class and has its own implementation of the base class's property that is explicitly hidden using the New modifier. In the base class' method, is there a good way to use the inherited class' property instead of the base's implementation?
class Program
{
public class MyBase
{
public string MyProperty { get { return "Base"; } }
public string MyBaseMethod()
{
return MyProperty;
}
}
public class MyInherited : MyBase
{
public new string MyProperty { get { return "Inherited"; } }
}
static void Main(string[] args)
{
List<MyBase> test = new List<MyBase>();
test.Add(new MyBase());
test.Add(new MyInherited());
foreach (MyBase item in test)
{
Console.WriteLine(item.MyBaseMethod());
}
}
}
In the example, the output is:
Base
Base
Current workaround:
...
public class MyBase
{
public string MyProperty { get { return "Base"; } }
public string MyBaseMethod()
{
if (this is MyInherited)
{
return baseMethod(((MyInherited)this).MyProperty);
}
else
{
return baseMethod(MyProperty);
}
}
private string baseMethod(string input)
{
return input;
}
}
...
Is there a better way to do this? I'd rather not have to do explicit type casts.
Hiding a member with the new keyword should generally be avoided. Instead make the base class' property virtual and override it in the descending class. The MyBaseMethod will automatically use this overridden property in inheriting classes.
public class MyBase
{
public virtual string MyProperty { get { return "Base"; } }
public string MyBaseMethod()
{
return MyProperty;
}
}
public class MyInherited : MyBase
{
public override string MyProperty { get { return "Inherited"; } }
}
var inherited = new MyInherited();
Console.WriteLine(inherited.MyBaseMethod()); // ==> "Inherited"
See this interesting post related to the new keyword: Why do we need the new keyword and why is the default behavior to hide and not override?
Make the property virtual, not sealed, and override it, rather than shadowing it. Then all uses of the property will use the most derived implementation of it.
There is no such way. If you do new (which is early binding), you have to do explicit casts. The only solution is to make the property virtual. Then you can override it (using the override modifier). This is late binding.

how to specify optional anonymous ienumerable parameters in c# abstract method

I have the following base class
public abstract class BaseRepository<T>
{
public abstract IEnumerable<T> GetAll();
}
And a class the inherits it.
public class CustomerRepository: BaseRepository<Customer>
{
public override IEnumerable<Customer>GetAll()
{
return null;
}
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
what i want to do is using this class
public class Sales
{
public int Id { get; set; }
public int CustomerId {get;set;}
public decimal Total {get;set;}
}
this doesn't work
public class SalesRepository: BaseRepository<Sales>
{
public override IEnumerable<Sales>GetAll(IEnumerable<Customer> Customers)
{
return null;
}
}
My question is, how to I modify my BaseClass to have optional ienumerable parameters of that i can then use as needed.
The GetAll(IEnumerable<Customer> Customers) function amounts to a new method. It does not have the same signature of the base, and so cannot be overridden in this way. The SalesRepository class, if it is to be a BaseRepository<Sales>, must implement the GetAll() method as is.
You can do this change
public class SalesRepository : BaseRepository<Sales>
{
public override IEnumerable<Sales> GetAll()
{
return GetAll(null);
}
public IEnumerable<Sales> GetAll(IEnumerable<Customer> Customers)
{
return null;
}
}
BaseRepository<Sales> rep = new SalesRepository();
rep.GetAll();
this will call overridden version and makes a call to GetAll(null).
To pass value to GetAll() method you need to have do the following
SalesRepository srep = new SalesRepository();
srep.GetAll(new Customer[] { new Customer() });
You can either mark parameter as optional or you can make overloads to the method in your base class, both of which will result in the same thing. When you mark a parameter as optional the compiler simply makes the overloads for you.
Ultimately you probably need to make two methods in your base class and then either hide one (make private) in your implementation of each parent class or have it throw an error. If you can figure out a good way to have default values then that may work as well.

Categories

Resources