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.
}
}
Related
I was recently working on a project where I needed to have the following functionality:
public interface IStart
{
public void StartStarting();
public bool IsDoneStarting();
}
public interface IEnd
{
public void StartEnding();
public bool IsDoneEnding();
}
These two interfaces basically do the same thing:
public interface IDo
{
public void StartDoing();
public bool IsDoneDoing();
}
Is there somehow a way to inherit IDo twice rather than IStart and IEnd individually? I highly doubt it, but it would certainly be convenient.
Another option to consider is using composition over inheritance. In a composition scenario, the IStart and IEnd implementations would be passed in to the .ctor, then accessed as properties.
Code is worth a thousand words...
public interface IDo
{
void StartDoing();
bool IsDoneDoing();
}
public interface IStart : IDo { }
public interface IEnd : IDo { }
public interface IWorker
{
IStart Start { get; }
IEnd End { get; }
}
public class Worker : IWorker
{
public IStart Start { get; }
public IEnd End { get; }
public Worker( IStart start, IEnd end )
{
Start = start;
End = end;
}
}
It can't be done to inherit one interface to the next. If you want a commonality expressed as such, I suggest using an abstract class which pulls in both interfaces and expresses that syntactic sugar you seek as such:
public abstract class IDo : IStart, IEnd
{
public void StartDoing() { StartStarting(); }
public bool IsDoneDoing() { return IsDoneEnding() }
public virtual void StartStarting() {}
public virtual bool IsDoneStarting() { return false; } // Override me.
public virtual void StartEnding() { }
public virtual bool IsDoneEnding() { return false; } // Override me.
}
I'm trying to create an interface to a class i have in c++cli which is then consumed in c#.
Basically, I want to do something along the lines of:
public interface class IFoo
{
static int method();
};
public ref class Foo : public IFoo
{
static int method() { return 0; }
};
So obviously this is incorrect, as there will be errors when trying to compile. I've tried numerous different ways, to no avail.
In c#, i would do the following:
public interface IFooCSharp
{
int method();
}
public class FooCSharp : IFooCSharp
{
public static int method() { return 0 };
int IFooSharp.method() { return FooCSharp.method(); }
}
So i was hoping to see if there was an equivalent way to do this in c++cli?
You can't have static members in an interface.
You figured out the right way to do this in C#: through an explicit interface implementation, you just need the right syntax for C++/CLI:
public interface class IFoo
{
int method();
};
public ref class Foo : public IFoo
{
static int method() { return 0; }
virtual int methodInterface() sealed = IFoo::method { return method(); }
};
Unlike in C#, you need to provide a name for your method, even though you don't intend to use it directly.
Here's the syntax for properties:
public interface class IFoo
{
property int prop;
};
public ref class Foo : public IFoo
{
property int propInterface {
virtual int get() sealed = IFoo::prop::get { return 0; }
virtual void set(int value) sealed = IFoo::prop::set { /* whatever */ }
};
};
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();}}
}
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...
}
}
Without any code in the subclasses, I'd like an abstract class to have a different copy of a static variable for each subclass. In C#
abstract class ClassA
{
static string theValue;
// just to demonstrate
public string GetValue()
{
return theValue;
}
...
}
class ClassB : ClassA { }
class ClassC : ClassA { }
and (for example):
(new ClassB()).GetValue(); // returns "Banana"
(new ClassC()).GetValue(); // returns "Coconut"
My current solution is this:
abstract class ClassA
{
static Dictionary<Type, string> theValue;
public string GetValue()
{
return theValue[this.GetType()];
}
...
}
While this works fine, I'm wondering if there's a more elegant or built-in way of doing this?
This is similar to Can I have different copies of a static variable for each different type of inheriting class, but I have no control over the subclasses
There is a more elegant way. You can exploit the fact that statics in a generic base class are different for each derived class of a different type
public abstract class BaseClass<T> where T : class
{
public static int x = 6;
public int MyProperty { get => x; set => x = value; }
}
For each child class, the static int x will be unique for each unique T
Lets derive two child classes, and we use the name of the child class as the generic T in the base class.
public class ChildA: BaseClass<ChildA>
{
}
public class ChildB : BaseClass<ChildB>
{
}
Now the static MyProperty is unique for both ChildA and ChildB
var TA = new ChildA();
TA.MyProperty = 8;
var TB = new ChildB();
TB.MyProperty = 4;
While this works fine, I'm wondering if there's a more elegant or built-in way of doing this?
There isn't really a built-in way of doing this, as you're kind of violating basic OO principles here. Your base class should have no knowledge of subclasses in traditional object oriented theory.
That being said, if you must do this, your implementation is probably about as good as you're going to get, unless you can add some other info to the subclasses directly. If you need to control this, and you can't change subclasses, this will probably be your best approach.
This is a little different than what you're asking for, but perhaps accomplishes the same thing.
class Program
{
static void Main(string[] args)
{
Console.WriteLine((new B()).theValue);
Console.WriteLine((new C()).theValue);
Console.ReadKey();
}
}
public abstract class A
{
public readonly string theValue;
protected A(string s)
{
theValue = s;
}
}
public class B : A
{
public B(): base("Banana")
{
}
}
public class C : A
{
public C(): base("Coconut")
{
}
}
There's an alternative solution which might or might not be better than yours, depending on the use case:
abstract class ClassA
{
private static class InternalClass<T> {
public static string Value;
}
public string GetValue()
{
return (string)typeof(InternalClass<>)
.MakeGenericType(GetType())
.GetField("Value", BindingFlags.Public | BindingFlags.Static)
.GetValue(null);
}
}
This approach is used in EqualityComparer<T>.Default. Of course, it's not used for this problem. You should really consider making GetValue abstract and override it in each derived class.
What about this?
class Base {
protected static SomeObjectType myVariable;
protected void doSomething()
{
Console.WriteLine( myVariable.SomeProperty );
}
}
class AAA : Base
{
static AAA()
{
myVariable = new SomeObjectType();
myVariable.SomeProperty = "A";
}
}
class BBB : Base
{
static BBB()
{
myVariable = new SomeObjectType();
myVariable.SomeProperty = "B";
}
}
It works for me.
Would be even nicer with Interface.
Simple solution: just use word "new".
public abstract class AbstractClass
{
public static int Variable;
}
public class RealizationA : AbstractClass
{
public new static int Variable;
}
public class RealizationB : AbstractClass
{
public new static int Variable;
}
And the result:
AbstractClass.Variable = 1;
RealizationA.Variable = 2;
RealizationB.Variable = 3;
Console.WriteLine(AbstractClass.Variable); //1
Console.WriteLine(RealizationA.Variable); //2
Console.WriteLine(RealizationB.Variable); //3
or you can use property:
//in abstract class
public static int Variable {get; set;}
//in child class
public static new int Variable {get; set;}
or function (but remember to add "new" to both variable and function):
//in abstract class
protected static int Variable;
public static int GetVariable() { return Variable; }
public static void SetVariable(int v) { Variable = v; }
//in child class
protected new static int Variable;
public static new int GetVariable() { return Variable; }
public static new void SetVariable(int v) { Variable = v; }
or you can use private variables (you don't need to use "new") with functions to get and set:
//in abstract class
private static int Variable;
//get and set methods
//in child class
private static int Variable;
//get and set methods