I have abstract base class that contains some fields and some methods that act on these fields. For example:
public abstract class A
{
protected double _field;
public double SquaredField { get { return _field * _field; } }
... some other abstract methods
}
I want to impose that all children of A initialize _field in their constructors
public class B : A
{
public B(double field)
{
_field = Math.Sqrt(field);
}
... some other method implementations
}
What's the correct pattern to achieve this?
-- EDIT
What I ended up doing is:
public abstract class A
{
protected readonly double _field;
public A(double field)
{
_field = field;
}
public double SquaredField { get { return _field * _field; } }
... some other abstract methods
}
public class B : A
{
public B(double field) : base(field)
{
}
public static B CreateNew(double val)
{
return new B(Math.Sqrt(field));
}
... some other method implementations
}
Don't expose a field to the derived classes at all. Instead, create a protected abstract property:
public abstract class A
{
protected double Field { get; }
public double SquaredField { get { return Field * Field; } }
}
Or, if the field should always be constant for a particular instance, make it a constructor parameter and keep it private:
public abstract class A
{
private readonly double _field;
public double SquaredField { get { return _field * _field; } }
protected A(double field)
{
_field = field;
}
}
Don't let class A have a parameterless constructor:
public abstract class A
{
protected double _field;
public double SquaredField { get { return _field * _field; } }
// Require any fields that must be initialized in the base class's
// constructor. If there are a lot of such fields, consider encapsulating
// them all in their own class, e.g. AArgs.
protected A(double field)
{
_field = field;
}
}
public class B : A
{
// You must call a base class constructor as below, because class A
// no longer has a parameterless constructor to use by default.
public B(double field)
: base(field)
{
}
}
Addendum
If you can't do the initialization in the constructor, you could make the field into an abstract property:
public abstract class A
{
protected abstract double Field { get; }
public double SquaredField { get { return Field * Field; } }
}
Now, the derived class has to implement the property, so you'll have it ready for the dependent SquaredField property. I would change the name though, since they're not fields anymore.
That's likely a signal that group of fields is more tightly coupled than A itself, and so should be moved to a class, say, AParams.
Then in A you can declare an abstract protected AParams createParams() method.
You could use a separate abstract function to accomplish this. The subclasses would be forced to implement it.
public abstract class A
{
protected double _field;
protected A()
{
InitializeField();
}
protected abstract void InitializeField();
public double SquaredField { get { return _field * _field; } }
}
public class B : A
{
protected override void InitializeField()
{
// Initialize...
}
}
Related
Hi i'm new in C# console application and i'm using abstract and override but i get stack in the first method in public abstract double Compute() i got an error and it says cannot declare a body because it is marked abstract please help me. thank you!
`
abstract class Cake
{
public string _flavor, _size;
public int _quantity;
public Cake(string flavor, string size, int quantity)
{
_flavor = flavor;
_size = size;
_quantity = quantity;
}
public abstract double Compute()
{
double price;
if(_flavor == "Chocolate" && _size == "Regular")
{
price = 250.50;
}
else if (_flavor == "Chocolate" && _size == "Large")
{
price = 450.50;
}
else if (_flavor == "Strawberry" && _size == "Regular")
{
price = 300.50;
}
else
{
price = 500.75;
}
return price;
}
}
class BirthdayCake:Cake
{
public int _numOfCandles;
public BirthdayCake(string flavor, string size, int quantity, int numOfCandles):base(flavor,size,quantity)
{
_numOfCandles = numOfCandles;
}
public override double Compute()
{
return _numOfCandles * 10.00;
}
}`
Use virtual instead of abstract when you have a default implementation but would like to allow sub-classes to override
As said, you can't declare a body for an abstract function of an abstract class.
You need to create another class herited from your abstract class that declare the body you want.
abstract class Cake
{
public string _flavor, _size;
public int _quantity;
abstract public double Compute();
}
class BirthdayCake : Cake
{
public int _numOfCandles;
public BirthdayCake(string flavor, string size, int quantity, int numOfCandles):base(flavor,size,quantity)
{
_numOfCandles = numOfCandles;
}
public override double Compute()
{
//does your stuff
}
}
abstract class is a class in which you can have functions which are abstract.
abstract function is a function inside an abstract class that has no body and also it forces you to override it in the derived class.
Your issue here is that you wrote an abstract function that has a body.
Fix: Use virtual keyword instead of abstract. virtual don't force you to override the function and you can also have a body in your base class.
(NB: If you are using virtual function instead of abstract function remove the abstract keyword from your class too.)
Abstract methods have no implementation in the same class, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. e.g:
Abstract methods have no implementation in the same class-Sample code
public abstract class A
{
public abstract void DoWork(int i);
public String DoWork(String str)
{
return str;
}
}
public class B:A
{
public virtual void DoWork(int i)
{
// here implementation.
}
}
I have next code
class Base
{
public virtual int Prop { get; set; }
}
class Derived : Base
{
public override int Prop { get { return 1; } }
}
//...
Derived obj = new Derived();
int some = obj.Prop; //expected
obj.Prop = 10; //oops it works
The fact that the last line should complile seems not to be so obvious at first sight. In my program I have a situation when overriding some auto-implemented property in a such way would be a solution. I understand that it's not a good approach. What kind of refactoring can I do to avoid such inheritance and to clean my code? Thanks
A derived class has to implement the same interface as its base class - having a public setter be inaccessible from a derived class would break polymorphism.
If Prop needs to be inaccessible to clients, but you need to be able to set its value from within the class itself, you could declare it as:
public virtual int Prop { get; protected set; }
There probably isn't a single answer to this question, as it depends on the model for your specific application. If some derived classes need to allow writes to this property, but others don't, you could either throw an exception on an invalid write and handle it at run time, or perhaps implement the property using a protected backing field and only a getter, and then add a derived class that provides a SetProp() method for those classes that need it.
public class Base
{
protected int prop;
public virtual int Prop { get { return prop; } }
}
public class WriteableBase : Base
{
public virtual void SetProp(int prop) { this.prop = prop; }
}
class Base
{
public virtual int Prop { get; set; }
}
class Derived : Base
{
public new int Prop { get { return 1; } private set {} }
}
The problem is that if you cast your Derived to Base, you can set the property anyway. If the Property relay on a field, it will be overwriten.
Ex.:
class Base
{
protected int fProp;
public virtual int Prop { get { return fProp; } set { fProp = value; } }
}
class Derived : Base
{
public Derived()
{
fProp = 1;
}
public new int Prop { get { return fProp; } private set {} }
}
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//...
Derived obj = new Derived();
int some = obj.Prop; //expected
Base b = (Base)obj;
b.Prop = 10; //oops it works
Console.WriteLine(obj.Prop); =>it will show 10, not 1
Console.ReadKey();
}
}
}
A "better" approach to avoid this kind of problem is to avoid the use of a base class if you want to "change" something on a derived class. Or, put only the minimal content that must be implemente by ALL derived classes and let the derived classes implement any extra code that only they want.
Ex:
class Base
{
protected int fProp;
}
class Derived : Base
{
public Derived()
{
fProp = 1;
}
public int Prop { get { return fProp; } }
}
class Derived2 : Base
{
public int Prop { get { return fProp; } set { fProp = value; } }
}
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//...
Derived obj = new Derived();
int some = obj.Prop; //expected
Base b = (Base)obj;
//obj.Prop = 10; Compilation error
Console.WriteLine(obj.Prop);
Derived2 obj2 = new Derived2();
obj2.Prop = 10;
Console.WriteLine(obj2.Prop);
Console.ReadKey();
}
}
}
Also, you could "encapsulate" your base class:
class Derived
{
protected Base fBase;
public Derived()
{
fBase = new Base;
}
//implement enything that you need to access from Base class
public int Prop { get { return 1; } }
}
But I find this last one too "expensive"... :)
I think it´s not possible to get compiler-error in this case. Imagine further you´d declare obj not as Derived but as Base = new Derived(), how should compiler know which property to infer. So all you can do is to throw an exception during runtime within the derived setter telling that setting this property isn´t allowed fir this type.
class Base
{
public virtual int Prop { get; protected set; }
}
class Derived : Base
{
public override int Prop {
get { return 1; }
protected set {throw NotSupportedException();}
}
}
When compiling, C# transforms the getter and setter to individual methods (get_Prop and set_Prop).
Your code only implements the get in the Derived class, and the setremains that of the base class.
If this is your desired behavior, I don't find it to be wrong.
If you are trying to hide the setter in the Derived class, there is no elegant way to do it, so throwing an NotSupportedException is a solution.
class Base
{
public virtual int Prop { get; set; }
}
class Derived : Base
{
public override int Prop { get { return 1; } set { throw new NotSupportedException();}}
}
Is there a way to hide/show a method if a certain constructor is used? i.e.:
public class SomeClass
{
public SomeClass(string methodA)
{
}
public SomeClass(int methodB)
{
}
public string MethodA()
{
return "";
}
public int MethodB()
{
return 0;
}
}
if SomeClass(string methodA) is used, then only MethodA() is available when I instance a new SomeClass object? The same when SomeClass(int methodB) is used, then MethodB() would be available?
Thank you all!
No, it's not possible.
What's more likely is that you want to use generics:
public interface IFoo<T>
{
T Method();
}
public class IntFoo : IFoo<int>
{
int value;
public IntFoo(int value)
{
this.value = value;
}
public int Method()
{
return value;
}
}
public class StringFoo : IFoo<string>
{
string value;
public StringFoo(string value)
{
this.value = value;
}
public string Method()
{
return value;
}
}
If you don't need to restrict it to just strings or ints (or don't want to) then something like this might work, or even be better:
public class Foo<T>
{
private T value;
public Foo(T value)
{
this.value = value;
}
public T Method()
{
return value;
}
}
No. This is not possible. You'd be better off creating an abstract class, and creating two separate classes inheriting from the Abstract Class. Refer to Abstract Design Pattern.
You may be better off using generics for your class. It's a bit less fluid than you're probably looking for (because you have to define the type in the class declaration), but accomplishes what you mainly want, I think.
public class SomeClass<T>
{
public SomeClass(T value)
{
}
public T Method() { return default(T); }
}
Which means that creating an instance of the class would use "new SomeClass(0);" rather than simply "new SomeClass(0);"
Suppose that we would like to separate out the read and write access in an interface pattern as below.
namespace accesspattern
{
namespace ReadOnly
{
public interface IA { double get_a(); }
}
namespace Writable
{
public interface IA : ReadOnly.IA { void set_a(double value); }
}
}
This is easy to implement:
namespace accesspattern
{
namespace ReadOnly
{
public class A : IA
{
protected double a;
public double get_a() { return a; }
}
}
namespace Writable
{
public class A : ReadOnly.A, IA
{
public void set_a(double value) { base.a = value; }
}
}
}
Suppose that we need another class which inherits from A and so we go ahead and define an interface for it:
namespace accesspattern
{
namespace ReadOnly
{
public interface IB : ReadOnly.IA { int get_b(); }
}
namespace Writable
{
public interface IB : ReadOnly.IB, Writable.IA { void set_b(int value); }
}
}
Implementing this is not so easy. One always feels that Writable.B should inherit from two base classes, Writable.A and ReadOnly.B, to avoid repeated code.
Is there a recommended Design Pattern to use? The aim is to be able to return "read access only" and "read write access" objects separately (decided at compile time) depending on requirements. It would be nice if the solution pattern makes it easy to add more layers of inheritance, classes C, D...
I know that the issue of Multiple Inheritance crops up here and that it has been discussed at length elsewhere in many, many, places. But my question is not so much "How to implement the interfaces which are defined inside the namespace accesspattern without using multiple inheritance" (although I would like to learn the best way to do that) but rather, how can we define the ReadOnly/Writable versions of a class separately and also support inheritance without it getting very, very, messy?
For what it is worth here is one (messy) solution [see below for much a better implementation]:
namespace accesspattern
{
namespace ReadOnly
{
public class A : IA
{
protected double a;
public double get_a() { return a; }
}
public class B : IB
{
protected int b;
public int get_b() { return b; }
}
}
namespace Writable
{
public class A : ReadOnly.A, IA
{
public void set_a(double value) { base.a = value; }
}
public class B : ReadOnly.B, IB
{
private IA aObj;
public double get_a() { return aObj.get_a(); }
public void set_a(double value) { aObj.set_a(value); }
public void set_b(int value) { base.b = value; }
public B() { aObj = new A(); }
}
}
}
}
Update: I think that this (below) is what Eugene is talking about. This implementation pattern is pretty good, I think. By only passing around "writeProtected" views of classes one can implement algorithms which require that the state of the class will not change and only use "writeEnabled" views where it is meant that the function will/could cause a change in state avoiding.
namespace access
{
// usual usage is at least readable
public interface IA { double get_a(); }
public interface IB : IA { int get_b(); }
// special usage is writable as well
namespace writable
{
public interface IA : access.IA { void set_a(double value); }
public interface IB : access.IB, IA { void set_b(int value);}
}
// Implement the whole of A in one place
public class A : writable.IA
{
private double a;
public double get_a() { return a; }
public void set_a(double value) { a = value; }
public A() { }
//support write-protection
public static IA writeProtected() { return new A(); }
public static writable.IA writable() { return new A(); }
}
// implement the whole of B in one place and now no issue with using A as a base class
public class B : A, writable.IB
{
private int b;
public double get_b() { return b; }
public void set_b(int value) { b = value; }
public B() : base() { }
// support write protection
public static IB writeProtected() { return new B(); }
public static writable.IB writable() { return new B(); }
}
public static class Test
{
static void doSomething(IA a)
{
// a is read-only
}
static void alterState(writable.IB b)
{
// b is writable
}
static void example()
{
// Write protected
IA a = access.A.writeProtected();
IB b = access.B.writeProtected();
// write enabled
writable.IA A = access.A.writable();
writable.IB B = access.B.writable();
Console.WriteLine(a.get_a());
B.set_b(68);
doSomething(A); // passed as writeprotected
alterState(B); // passed as writable
}
}
}
I know this thread is one year old, but I'm wondering if it would make sense to have something like this:
interface ReadOnlyA
{
object A { get; }
}
interface WriteableA : ReadOnlyA
{
new object A {get; set;}
}
You can provide the read/write access at Service level and not at Entity level. In that case you can code generate a wrapper around services that handles the read/write access.
Patterns used: Decorator, Dependency Injection
I got an abstract base class
public class Base
{
public abstract String Info { get; }
}
and some children.
public class A : Base
{
public override String Info { get { return "A does ..."; } }
}
public class B : Base
{
public override String Info { get { return "B does ..."; } }
}
This is mere a constant but I want to make sure using Base that all classes implement it.
Now I sometimes do not have an object instance but want to access A.Info - this is not possible due it is a instance property.
Is there another way than implementing the same property on instance AND on static level? That would be feel like a duplicate violating DRY programming style.
NEW EDIT: I now see this two solutions:
public class Base
{
public abstract String ClassInfo { get; }
}
public class A : Base
{
public override String ClassInfo { get { return Info; } }
public static String Info { get { return "A does ..."; } }
}
public class B : Base
{
public override String ClassInfo { get { return Info; } }
public static String Info { get { return "In B we do ..."; } }
}
With this I can do with any object of type Base something like object.ClassInfo but also use the value in my factory hardcoded like if(A.Info) return new A(). But I have to implement two properties for the same information in every class.
On the other hand:
public class Base
{
public abstract String ClassInfo { get; }
public static String GetClassInfo<T>() where T : BaseControl, new()
{
T obj = new T();
return obj.ClassInfo;
}
}
public class A : Base
{
public override String ClassInfo { get { return "text A"; } }
}
public class B : Base
{
public override String ClassInfo { get { return "text B"; } }
}
Due to the abstract Base it is made sure that ClassInfo is always implemented. Calls with obj.ClassInfo and Base.GetClassInfo<A>() are okay. But with this every child of Base must have a default constructor without arguments and we loose performance with the unneccessary created instance.
Is there any other idea? Which one would you prefer and why?
If you need specific return results of your static properties, you're better of either
a) Instance properties
2) Attributes
In the example you've already given, you've got an instance of Base, which means you can just make the instance property virtual:
public class Base
{
public virtual string Info { get { return "From Base"; } }
}
public class A : Base
{
public override string Info { get { return "From A"; } }
}
If you wanted to go the attribute route, you define it as such:
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class InfoAttribute : Attribute
{
public InfoAttribute(string info) { this.Info = info; }
public string Info { get; private set; }
}
[InfoAttribute(Info = "From Base")]
public class Base
{
public string GetInfo()
{
var attr = GetType()
.GetCustomAttributes(typeof(InfoAttribute), true)
.FirstOrDefault();
return (attr == null) ? null : attr.Info;
}
}
[InfoAttribute(Info = "From A")]
public class A : Base { }
If you wanted to call it as a static function call, you could make this change:
public static string GetInfo(Base instance)
{
var attr = instance.GetType()
.GetCustomAttributes(typeof(InfoAttribute), true)
.FirstOrDefault();
return (attr == null) ? null : attr.Info;
}
And then call it as: Base.GetInfo(instance);. All in all, not very elegant!
This is not possible.
static members cannot be virtual or abstract.
You should make an abstract instance property.
Statics can't be overridden. If you truly want to do something like that, you'd want an instance property that is virtual in the base that gets overridden in the subclasses.
Does it compiled? I don't think so. Static cannot be marked as override, virtual or abstract.