Call base class override method from base constructor C# - c#

I want to have class which will have an indexer and number of fields like in the following example:
public abstract class ARecord
{
public abstract double this[int index] { get; }
public abstract int NumberOfFields { get; }
}
public class Record : ARecord
{
public double Field1{ get; private set; }
public double Field2{ get; private set; }
public override int NumberOfFields { get { return 2; } }
public Record(double[] records)
{
if (records.Count() != NumberOfFields) // PROBLEM IS HERE. WHEN CALLING THIS FROM DERIVED CLASS NumberOfFields=3!
throw new ArgumentException();
this.Field1= records[0];
this.Field2 = records[1];
}
public override double this[int index]
{
get { throw new NotImplementedException(); }
}
}
public class ChildRecord : Record
{
public double Field3 { get; private set; }
public override int NumberOfFields { get { return 3; } }
public ChildRecord(double[] records)
: base(new double[] { records[0], records[1] })
{
if (records.Count() != NumberOfFields)
throw new ArgumentException();
this.Field3 = records[2];
}
public override double this[int index]
{
get { throw new NotImplementedException(); }
}
}
public static class TestRecord
{
public static void CreateRecord()
{
var record = new ChildRecord(new double[]{1.0,1.5,2.5}); // Not working
}
}
This example crashes because of polymorphic call NumberOfFields from ChildRecord inside constructor of Record.
As far as I know, I can use new insted of override to solve this problem, but in that case I cannot declare NumberOfFields as abstract in base class (which I needed).
What is the proper way to solve this problem? Is something wrong with the design?

The way you've formulated this, it cannot possibly work as intended. Assume it did (through some sort of some magic) work the way you think it should, and you were able to create your ChildRecord:
var record = new ChildRecord(new double[] { 1.0, 1.5, 2.5 });
What would you expect the value of record.NumberOfFields to be? Two or three? This particular object cannot be a ChildRecord with NumberOfFields == 3 and at the same time be a Record with NumberOfFields == 2. You get the result of the NumberOfFields implementation of the instantiated class, regardless of whether you type record as ARecord, Record or ChildRecord.
To put it another way: It makes no sense to expose ARecord.NumberOfFields to the outside, as there is no one correct answer -- it isn't a meaningful concept.
If you abstain from exposing it, you can do your validation something like this (with indexers and properties omitted):
public abstract class ARecord
{
public abstract double this[int index] { get; }
}
public class Record : ARecord
{
private const int NumberOfFields = 2;
public Record(double[] records)
{
if (records.Count() != NumberOfFields)
throw new ArgumentException();
this.Field1 = records[0];
this.Field2 = records[1];
}
}
public class ChildRecord : Record
{
private const int NumberOfFields = 3;
public ChildRecord(double[] records)
: base(new double[] { records[0], records[1] })
{
if (records.Count() != NumberOfFields)
throw new ArgumentException();
this.Field3 = records[2];
}
}

Related

C# SOLID - Extend class and override/hide members without violating Open/Closed?

I need to extend a class where the child class will not use some members of the parent class. How should the unused members be handled and still respect the open/closed SOLID principle? I'm considering doing something like the code below, but existing code that uses reflection will get exceptions. If I put data in the deprecated members, existing code will produce unexpected results.
I feel that a totally different approach should probably be used. How to handle this situation without modifying existing code (which would also violate the open/closed principle)?
class Parent
{
public virtual int myVarMin { get; set; } = 0;
public virtual int myVarMax { get; set; } = 10;
public int myVar { get; set; }
public int unchanged1 {get; set;}
//.
//numerous other members that are irrelevant to the question
//.
public void doSomething(){/*do something*/}
//
}
class Child:Parent
{
//considered impementation from original question
public override int myVarMin => throw new NotSupportedException();
public override int myVarMax => throw new NotSupportedException();
public List<int> myVarList = new List<int>();
}
class MyExistingCode
{
public void Display(Parent parent)
{
foreach (var info in parent.GetType().GetProperties())
{
Console.WriteLine($"{info.Name}: {info.GetValue(parent)}");
}
}
}
Use the Obsolete attribute to inform the developers that your method is deprecated and they should use the new version.
[Obsolete("Method is deprecated, use Method2 please.")]
public void Method()
{
…
}
Here I've changed your code, so using reflection you can detect whether a method/property is deprecated or not, and it'll not throw an exception anymore.
public class Parent
{
public virtual int myVarMin { get; set; } = 0;
public virtual int myVarMax { get; set; } = 10;
public int myVar { get; set; }
}
public class Child : Parent
{
[Obsolete("Use other property")]
public override int myVarMin => throw new NotSupportedException();
[Obsolete("Use other property")]
public override int myVarMax => throw new NotSupportedException();
public List<int> myVarList = new List<int>();
}
class MyExistingCode
{
public void Display(Parent parent)
{
foreach (var info in parent.GetType().GetProperties())
{
var customeAttributes = (ObsoleteAttribute[])info.GetCustomAttributes(typeof(ObsoleteAttribute), false);
if (customeAttributes.Length > 0)
{
Console.WriteLine($"{info.Name} is deprecated.");
}
else
{
Console.WriteLine($"{info.Name}: {info.GetValue(parent)}");
}
}
}
}
I ended up doing something like this (the Parent and MyExistingCode classes were unchanged, so they comply with the open/closed principle):
class Child : Parent
{
public new int? myVarMin => null;
public new int? myVarMax => null;
public List<int> myVarList = new List<int>();
}
class MyNewCode : MyExistingCode
{
public new void Display(Parent parent)
{
foreach (var info in parent.GetType().GetProperties())
{
Console.WriteLine($"{info.Name}: {info.GetValue(parent) ?? "NULL"}");
}
}
}
I was surprised that I could hide an int with an int? without an error.
I will Accept another answer if it is better.

Cast object from an interface to its implementation

I have the following code:
public interface BaseInterface
{
int ID { get; }
}
public interface SpecialInterface1 : BaseInterface
{
int price { get; }
}
public interface SpecialInterface1 : BaseInterface
{
int xyz { get; }
}
public class Implementation1 : SpecialInterface
{
int price { get; }
int ID { get; internal set; }
}
public class Implementation2 : SpecialInterface
{
int xyz { get; }
int ID { get; internal set; }
}
Now in a Management class I want to add the objects that implement BaseInterface into a List.
I know that I can use as or is to cast the interface to an implementation, but in my project, I have about 10 special interfaces with an implementation each so I would have to write a really big if statements.
public void Add(BaseInterface u, int id)
{
if (u is Implementation1)
{
((Implementation1)u).ID = id;
Units.Add(u);
}
if (u is Implementation2)
{
((Implementation2)u).ID = id;
Units.Add(u);
}
}
My goal is that the id is not changeable outside the implementation and I would provide only the interfaces outside my dll so none can change the id.
A solution would be to add an extra interface. This eliminates the internal setter in your implementation.
internal interface IChangeID
{
void SetID(int id);
}
public interface IBaseInterface
{
int ID { get; }
}
public class Implementation : IBaseInterface,
IChangeID
{
public void SetID(int id) { ID = id; }
public int ID { get; private set; }
}
Only the real implementations should implement IChangeID. Returning IBaseInterface or ISpecialInterface will hide the setter, because those interfaces do not inherit from IChangeID.
This would change your add into:
public void Add(BaseInterface u, int id)
{
((IChangeID)u).SetID(id);
Units.Add(u);
}
If you do want to return the concrete types, not interfaces. You could implement the given interface explicit. This will hide the set method even from the concrete implementation.
public class Implementation : IBaseInterface,
IChangeID
{
void IChangeID.SetID(int id) { ID = id; }
public int ID { get; private set; }
}
var obj = new Implementation();
obj.SetID() // This WILL NOT Compile
If you don't want to modify the interfaces and implementations, you could use C# 7's pattern matching to access the implementation type without casting. It requires 3 lines per implementation type but avoids modifying the classes:
public void Add(BaseInterface u, int id)
{
switch(u)
{
case Implementation1 u1:
u1.ID = id;
break;
case Implementation2 u1:
u1.ID = id;
break;
default :
throw new ArgumentException("Unexpected implementation!");
}
Units.Add(u);
}
The obvious disadvantage is that the code will have to be modified if a new implementation is added.
Another option is to use dynamic, losing type safety. This will fail at runtime if some implementation doesn't have a setter (eg because it was replaced by constructor initialization)
public void Add(BaseInterface u, int id)
{
dynamic x =u;
x.ID=id;
Units.Add(x);
}
While I like this answer the best,
I recommend making the ID a required parameter of all the implementation's constructors, and then to use a factory pattern to generate any instance you require. This makes any instance without the ID set throw an exception at compile time rather than runtime reducing the probability of exceptions.
Here is a simple example that gets you what you want without an additional interface. Should you choose you can combine my answer with #Iqon's answer.
public interface IInterface
{
int ID { get; }
}
internal class InternalImplementation: IInterface {
public InternalImplementation(int ID) { this.ID = ID; }
public int ID { get; set; }
}
public class MyImplementationFactoryService {
public IInterface Create() {
int id = 1 // Or however you get your ID, possibly from a DB query?
return new InternalImplementation(id);
}
public IInterface Create(type|enum createtype) {
// return type based on typeof or enum
}
}
In case you want to use reflection to set property, code below may help
public interface IBaseInterface
{
int ID { get; }
}
public class Impl1 : IBaseInterface
{
public int ID { get; internal set; }
public int Price {get; set;}
}
public class Impl2 : IBaseInterface
{
public int ID { get { return 0;} }
public int Subscription {get; set;}
}
public class Program
{
public static void Main(string[] args)
{
IBaseInterface obj1 = new Impl1();
SetProperty(obj1, "ID", 100);
Console.WriteLine("Object1 Id is {0}", obj1.ID);
IBaseInterface obj2 = new Impl2();
SetProperty(obj2, "ID", 500);
Console.WriteLine("Object2 Id is {0}", obj2.ID);
}
private static void SetProperty(IBaseInterface obj, string propertyName, object id){
if(obj.GetType().GetProperty(propertyName).CanWrite) {
obj.GetType().GetProperty(propertyName).SetValue(obj, id);
Console.WriteLine("CanWrite property '{0}' : {1}" , propertyName, obj.GetType().GetProperty(propertyName).CanWrite);
}
}
}
Output
CanWrite property 'ID' : True
Object1 Id is 100
Object2 Id is 0

C# Can't access inherited protected variable from Generic class

First time poster...
New to C# and Generics and I have been experimenting by creating a simple series of Object Tables for read-only data entries.
On my Generic Insert routine I increment a static Id variable to ensure it is always unique. To try and prevent it being modified I set it to protected but the Generic class which then throws a compile error stating that Id can't be accessed.
I am struggling to find out why exactly as I thought "where T : DBEntity" would allow this.
Thanks in advance:
public class DBEntity
{
public int Id { get; protected set; }
}
public class Table<T> where T : DBEntity
{
static int _id = 0;
private readonly List<T> _set = new List<T>();
public IEnumerable<T> Set() { return _set; }
public void Insert(T item)
{
_id++;
item.Id = _id; //when set to protected it is inaccessible
_set.Add(item);
}
}
You're protecting the ID, so you can't set it. It's honestly as simple as that.
Also doing a generic of Table, and tying the generic to a concrete class buys you nothing. Consider an interface instead.
You could fix your issue as the following:
public interface IDatabaseItem
{
int? Id { get; }
SetID(int value);
}
public class DBEntity : IDatabaseItem
{
public int? Id { get; private set; }
public void SetID(int value)
{
if (Id == null)
{
Id = value;
}
else
{
throw new Exception("Cannot set assigned Id; can only set Id when it is not assgined.");
}
}
}
public class Table<T> where T : IDatabaseItem
{
static int _id = 0;
private readonly List<T> _set = new List<T>();
public IEnumerable<T> Set() { return _set; }
public void Insert(T item)
{
if (item.Id == null)
{
_id++;
item.SetID(_id);
_set.Add(item);
}
else
{
//Handle this case. Something else set the ID, yet you're trying to insert it. This would, with your code, imply a bug.
}
}
}

C#: Confusion about Interfaces, Implementation and Inheritance

I'm wondering about what's the way to go, if I need to publicate data-interfaces but want to use them internal with extended calculated properties. To make it clearer:
// The public interface
public interface IData
{
int Property { get; }
}
// The internal interface
internal interface IExtendedData : IData
{
int ExtendedProperty { get; }
}
// The assumed implementation of someone using my interface
public class Data : IData
{
public Data(int a)
{
Property = a;
}
public int Property
{
get;
private set;
}
public override string ToString()
{
return Property.ToString();
}
}
// My implementation
internal class ExtendedData : IExtendedData
{
public ExtendedData(int a)
{
Property = a;
}
public int Property
{
get;
private set;
}
public int ExtendedProperty
{
get
{
return 2 * Property;
}
}
public override string ToString()
{
return Property.ToString() + ExtendedProperty.ToString();
}
}
// publicated by me, for the person who uses my dll
public static class Calculations
{
public static int DoSomeCalculation(IData data, int parameter)
{
// This probably don't work, but maybe shows what I want to do
IExtendedData tempData = (ExtendedData)data;
return tempData.ExtendedProperty * parameter;
}
}
I'm realy frustrated, cause I feel like missing some basical programing skills.
You could solve this problem by implementing ExtendedData as a Wrapper for a class implementing IData
internal class ExtendedData : IExtendedData
{
private IData data;
public ExtendedData(IData data)
{
this.data = data;
}
public int Property
{
get { return data.Property; }
private set { data.Property = value; }
}
public int ExtendedProperty
{
get
{
return 2 * Property;
}
}
}
and use this in DoSomeCalculation like
IExtendedData tempData = new ExtendedData(data);
ExtendedData could inherit from Data:
class ExtendedData : Data
{...}
And for creation of a Data object you add a factory like so:
public class DataFactory
{
public IData CreateData()
{
return new ExtendedData();
}
}
User have to create all its Data objects by this factory. You can ensure it by making Data's constructor internal.
In your DLL you can then cast to ExtendedData.

Override abstract readonly property to read/write property

I would like to only force the implementation of a C# getter on a given property from a base abstract class. Derived classes might, if they want, also provide a setter for that property for public use of the statically bound type.
Given the following abstract class:
public abstract class Base
{
public abstract int Property { get; }
}
If I want a derived class that also implements a setter, I could naively try:
public class Derived : Base
{
public override int Property
{
get { return field; }
set { field = value; } // Error : Nothing to override.
}
private int field;
}
But then I get a syntax error since I try to override the non existing setter. I tried some other way such as declaring the base setter private and such and I still stumble upon all kind of errors preventing me from doing that. There must be a way to do that as it doesn't break any base class contract.
Incidentaly, it can be done with interfaces, but I really need that default implementation.
I stumbled into that situation so often, I was wondering if there was a hidden C# syntax trick to do that, else I will just live with it and implement a manual SetProperty() method.
You can't do it directly, since you can't new and override with the same signature on the same type; there are two options - if you control the base class, add a second property:
public abstract class Base
{
public int Property { get { return PropertyImpl; } }
protected abstract int PropertyImpl {get;}
}
public class Derived : Base
{
public new int Property {get;set;}
protected override int PropertyImpl
{
get { return Property; }
}
}
Else you can introduce an extra level in the class hierarchy:
public abstract class Base
{
public abstract int Property { get; }
}
public abstract class SecondBase : Base
{
public sealed override int Property
{
get { return PropertyImpl; }
}
protected abstract int PropertyImpl { get; }
}
public class Derived : SecondBase
{
public new int Property { get; set; }
protected override int PropertyImpl
{
get { return Property; }
}
}
Would this suit your needs?
public abstract class TheBase
{
public int Value
{
get;
protected set;
}
}
public class TheDerived : TheBase
{
public new int Value
{
get { return base.Value; }
set { base.Value = value; }
}
}
The virtual was removed, but the base value is still the only storage for the value. So this should show '5'. And the compiler should fuss about b.Value = 4;
TheDerived d = new TheDerived();
d.Value = 5;
TheBase b = d;
//b.Value = 4; // uncomment for compiler error
cout << "b.Value == " << b.Value << endl;
-Jesse
What about something like:
public abstract class Base
{
public virtual int Property
{
get { return this.GetProperty(); }
set { }
}
protected abstract int GetProperty();
}
I had a similar requirement where I needed an interface to be able to share common sorting functionality between two loosely related classes. One of them had a read-only Order property and the other had a read-write Order property, but I needed a way to read the property the same way from both classes.
It turns out that this can be done by hiding the read-only value in a derived interface. Here is how I did it.
interface ISortable
{
int Order { get; }
}
interface ISortableClass2
: ISortable
{
// This hides the read-only member of ISortable but still satisfies the contract
new int Order { get; set; }
}
class SortableClass1
: ISortable
{
private readonly int order;
public SortableClass1(int order)
{
this.order = order;
}
#region ISortable Members
public int Order
{
get { return this.order; }
}
#endregion
}
class SortableClass2
: ISortableClass2
{
#region ISortableClass2 Members
public int Order { get; set; }
#endregion
}
class RunSorting
{
public static void Run()
{
// Test SortableClass1
var list1 = new List<SortableClass1>();
list1.Add(new SortableClass1(6));
list1.Add(new SortableClass1(1));
list1.Add(new SortableClass1(5));
list1.Add(new SortableClass1(2));
list1.Add(new SortableClass1(4));
list1.Add(new SortableClass1(3));
var sorted1 = SortObjects(list1);
foreach (var item in sorted1)
{
Console.WriteLine("SortableClass1 order " + item.Order);
}
// Test SortableClass2
var list2 = new List<SortableClass2>();
list2.Add(new SortableClass2() { Order = 6 });
list2.Add(new SortableClass2() { Order = 2 });
list2.Add(new SortableClass2() { Order = 5 });
list2.Add(new SortableClass2() { Order = 1 });
list2.Add(new SortableClass2() { Order = 4 });
list2.Add(new SortableClass2() { Order = 3 });
var sorted2 = SortObjects(list2);
foreach (var item in sorted2)
{
Console.WriteLine("SortableClass2 order " + item.Order);
}
}
private static IEnumerable<T> SortObjects<T>(IList<T> objectsToSort) where T : ISortable
{
if (objectsToSort.Any(x => x.Order != 0))
{
return objectsToSort.OrderBy(x => x.Order);
}
return objectsToSort;
}
}
You may do this with a constructor as following;
public abstract class Base
{
public abstract int Property { get; }
}
public class Derived : Base
{
public Derived(string Property) : base(Property)
{
}
}

Categories