I am trying to inherit abstract members from a derived class and it is not working.
I have set the class as abstract such as
Now my main program says the same thing about the CalculateWeeklyPay() and I shouldn't need it in my main class. How can I fix that?
// Pay method
public double CalculateWeeklyPay(double Hours, double Wage)
{
return Hours * Wage;
}
The parameter list to CalculateWeeklyPay is hiding the class members Hours and Wage. I suspect you want this instead:
// Pay method
public double CalculateWeeklyPay()
{
return Hours * Wage;
}
In fact, I would go a step further and make it a read-only property instead:
// Pay method
public double WeeklyPay
{
get { return Hours * Wage; }
}
output += "\n\t Weekly Pay:\t" + CalculateWeeklyPay().ToString("C2");
You define public double CalculateWeeklyPay(double Hours, double Wage),but in this function there are not two double number.It is wrong.
public override double CalculateWeeklyPay(){...}
abstract is like virtual except that a derived class must either override it or else must become abstract itself.
output += "\n\t Weekly Pay:\t" + CalculateWeeklyPay().ToString("C2");
CalculateWeeklyPay is expecting 2 arguments: Wage and Hours. Remove those arguments from the definition and it will work:
public override double CalculateWeeklyPay()
{
...
}
Related
so I have a problem:
When I'm trying to hand over a parameter from the Child-Class to the Base-Class, the parameter is not in the Base-Class:
public class Zeiteinheit : Shutdown_Time
{
public int Public_minuten
{
get { return _minuten; }
set { _minuten = value; }
}
public void Minuten_Zu_Sekunden_Umrechnung()
{
_sekunden = (_minuten * 60);
}
}
public class Shutdown_Time
{
protected int _sekunden;
protected string herunterfahrenTimer;
public string Public_herunterfahrenTimer
{
get { return herunterfahrenTimer; }
set { herunterfahrenTimer = $"-s -t {_sekunden}"; }
}
}
MainClass:
//Umrechnung der eingetragenen Zeit findet statt
obj_zeiteinheit.Minuten_Zu_Sekunden_Umrechnung();
//Herunterfahren mit der Umgerechneten Zeit von stunden in sekunden
System.Diagnostics.Process.Start("Shutdown", obj_shutdown_Time.Public_herunterfahrenTimer);
break;
Result of an debug
My Question is here, did i missunderstood something by the concept of inheriting or what is my mistake?
(Sorry for my very bad english, and thanks for the help!)
You seem to be asking "when I set a property or field in a base class, how do I trigger the updating of a property or field in a derived class?"
But then you showed code that outlines you want to set ZeitenHeit.Public_Minuten = 60, which does set _sekunden = 3600 but you then also want to update, in the same class, herunterfahrenTimer so it is -s -t 3600 because right now it isn't updated (the screenshot is null)
There is a small but critical difference between what you asked and what you appear to be trying to do, so you've essentially asked two questions. I'll deal with that one in the question title first:
how can a base class update a derived(child) class?
It can't; it doesn't even know it exists. The derived class knows the base class exists though, so you can use that instead
One way is to have the derived class override the setting function of the base class:
class MyBase{
int _myField;
virtual void SetMyField(int val){
_myField = val;
}
}
class MyDerived:MyBase{
string _myOtherField;
override void SetMyField(int val){
base.SetMyField(val);
_myOtherField = val.ToString();
}
}
In use, a variable of type MyBase holding an instance of type MyDerived, will set both values when you call SetMyField:
var mb = new MyDerived();
mb.SetMyField(1); //implementation on MyDerived is used, causing _myOtherField to be set
You might have the base class raise an event (or invoke a delegate) when it's property is set and the derived class subscribes to it
class MyBase{
int _myField;
event EventHandler<int> MyFieldUpdatedTo;
void SetMyField(int val){
_myField = val;
var e = MyFieldUpdatedTo;
e?.Invoke(this, val);
}
}
class MyDerived:MyBase{
string _myOtherField;
MyDerived(){ //constructor, or can also subscribe to event in the place that instantiates the MyDerived
base.MyFieldUpdatedTo += val => _myOtherField = val.ToString();
}
}
This is perhaps slightly unusual, though common to see in windows forms
However you arrange it, you need to leverage that the derived knows about the base but not the other way round, so anything done to the base needs to go via the derived, or via something that knows about both of them, or by creating a link from base to derived
In your specific case you're having a problem because the class that knows about both of your data items (the base class) only sets one of them
You could literally trigger the setting of the string by changing the value of the Public_herunterfahrenTimer to anything:
public void Minuten_Zu_Sekunden_Umrechnung()
{
_sekunden = (_minuten * 60);
Public_herunterfahrenTimer = ""; //any string, the value is not used
}
You could also put the setting of _sekunden into Public_herunterfahrenTimer and then set that property in the derived method
But structuring the code like this, and actually the code structure in general is very strange- we simply wouldn't write code like that. There is no need for a string property that duplicates information that is remembered in the _sekunden variable, and does do on the set, which naturally allows data to go out of sync
Instead you should perhaps just calculate the string in a get:
public class Zeiteinheit : ShutdownTime
{
public int Minuten
{
get { return _sekunden / 60; }
set { _sekunden = (value * 60); }
}
}
public class ShutdownTime
{
protected int _sekunden;
public string HerunterfahrenTimer
{
get { return $"-s -t {_sekunden}"; }
}
}
There is no possibility now for these to be out of sync; setting the minutes means the seconds are updated and the shutdown argument string will be generated when it is requested
note, I've also fixed your code up to regular C# conventions- strive to only use snake case on CONSTANTS_LIKE_THIS, don't prefix public things with "Public" and be consistent with the leading underscores on field names; all or none
I am trying to call a class inside my main that calculates the amount of Carprofen an animal need with a given formula. I cant get the right syntax to make the method call, is this because its from another class?
I am trying to use
Console.WriteLine($"\nYour pet requires {Carprofen(pet1)}ml of carprofen.");
Says that class Carprofen does not exist.
here is my Pet Class:
public double Carprofen(Pet pet1) //The function
{
if (pet1.Type == "Dog")
{
double dosage = ((pet1.Weight / 2.205) * (12 / 0.5));
return (dosage);
}
else
{
double dosage = ((pet1.Weight / 2.205) * (12 / 0.25));
return (dosage);
}
}
Use the name of the class then the method. If your class is in the different namespace, you have to provide the full path as well... namespace.class.method. also, you have to ensure both class and method are set up public if accessing outside your project
public class MyMethods{
public double Carporfen...
...
}
You would call it in any other class like below. Make sure to use toString to convert double to string for console display
Console.WriteLine($"{MyMethods.Carporfen(pet1).ToString()}ml");
I am setting up a class with a GUI and having issues on this mandatory ToString method I need in my code. I missed 2 classes due to traveling for a family emergency and now just a little lost on what exactly I am doing here.
Honestly, I don't understand much of whats going on, so I am looking for an explanation. But I have tried watching videos and moving around the code to no avail.
class Sandwich
{
public string name = "Tony";
public string meat = "None";
public int tomatoSlices = 1;
public override tomatoSlices.ToString()
{
public double ComputerPrice()
{
return 4.0 + (0.5 * tomatoSlices);
}
}
}
The program should run, but not sure why it isnt. It has something to do with the tomatoSlices integer, I suppose.
As mentioned in the comments you have declared a method inside another method. You need to move the ComputerPrice() outside of the ToString method. Also, you need to remove the tomatoSlices from the ToString definition:
class Sandwich
{
public string name = "Tony";
public string meat = "None";
public int tomatoSlices = 1;
public double ComputerPrice()
{
return 4.0 + (0.5 * tomatoSlices);
}
public override string ToString()
{
return ComputerPrice().ToString();
}
}
Now, when you call sandwich.ToString() it will return the value of ComputerPrices() as a string e.g.:
var sandwich = new Sandwich();
var price = sandwich.ToString();
It's a little hard to tell exactly what you want, but you have a method nested inside another method, which is not legal.
Probably you want to move ComputerPrice() out of the ToString() method, and then implement what you want for ToString() (which is typically the string representation of the class).
Also, you don't specify tomatoSlices as part of the method name; when you override a base class method, you just use the base class method name, which is ToString(). You also have to declare a return type of string for the method.
Other things you may want to do are:
Use public properties instead of fields
Use PascalCase for public members
Use the decimal datatype for working with currency (to avoid rounding errors)
Here's a sample class that addresses all these issues:
class Sandwich
{
public string Name { get; set; }
public string Meat { get; set; }
public int TomatoSlices { get; set; }
public Sandwich()
{
Name = "Tony";
Meat = "None";
TomatoSlices = 1;
}
public override string ToString()
{
return $"This sandwich named {Name} " +
$"has {Meat} meat and {TomatoSlices} slices of " +
$"tomato, for a total cost of {ComputerPrice()}";
// Or just return the price if that's what you want instead:
// return ComputerPrice().ToString();
}
public decimal ComputerPrice()
{
return 4M + 0.5M * TomatoSlices;
}
}
Who ya gonna call?
Unrelated code to pose the problem. Not the best editor tool so being terse. Thanks.
A new method that is part of the derived class cannot be accessed by the new
object. All the Intellisense sees are the abstract parts of the base class. Typing them in and running them gets an error. If methods and fields can't be added what is the point of base to derived and on down. I have searched all examples and come up empty.
public class SalesEmployee : Employee
{
public decimal salesbonus; // Additional field
public SalesEmployee(string name, decimal basepay, decimal salesbonus)
{
this.salesbonus = salesbonus; // Create new field
}
public override decimal CalculatePay() // Override abstract
{
return basepay + salesbonus;
}
public decimal CalculateExtraBonus() // Not an override
{
return basepay + (0.5 * salesbonus); // Belongs to this class only
}
}
static void Main()
{
// Create new employee.
SalesEmployee employee1 = new SalesEmployee("Alice", 1000, 500);
decimal = employee1.CalculateExtraBonus(); // Can't see the new method
// Derived class cannot get to new method.
}
I'm thinking of trying the following. Typing out questions really helps.
{ SalesEmployee salesEmpInstance = employee1
decimal = salesEmpInstance.CalculateExtraBonus()
// Maybe this could see the method.
I'll ignore the syntax errors and assume you have it right in your actual code. However it looks like you forgot to call the parents constructor ("base") on your derived class constructor and then tried to access a variable only instantiated by the parent. Also you need to cast the literal "0.5" as a decimal.
You can read more about "base" on msdn
Working code is below. Output is 1250.
using System;
public abstract class Employee
{
public string name;
public decimal basepay;
public Employee(string name, decimal basepay)
{
this.name = name;
this.basepay = basepay;
}
public abstract decimal CalculatePay();
}
public class SalesEmployee : Employee
{
public decimal salesbonus; // Additional field
// -->ERROR HERE, You forgot to call the base and instantiate
// the fields of the parent.
public SalesEmployee(string name, decimal basepay, decimal salesbonus): base(name, basepay)
{
this.salesbonus = salesbonus; // Create new field
}
public override decimal CalculatePay() // Override abstract
{
return basepay + salesbonus;
}
public decimal CalculateExtraBonus() // Not an override
{
return basepay + ((decimal)0.5 * salesbonus); // Belongs to this class only
}
}
class Program
{
static void Main(string[] args)
{
SalesEmployee employee1 = new SalesEmployee("Alice", 1000, 500);
decimal aliceBonus = employee1.CalculateExtraBonus();
Console.WriteLine(aliceBonus);
}
}
Your code looks fine, I recommend you:
Remove the reference to the first class library from your new project.
Rebuild your first class library
Reference again the first class library dll file in your new project, maybe you referenced to an older version of the dll. You should reference to the last created dll of first class library
Correct your code like this
.
{
SalesEmployee employee1 = new SalesEmployee("Alice", 1000, 500);
SalesEmployee salesEmpInstance = employee1 ;
decimal result = salesEmpInstance.CalculateExtraBonus();
}
Anyway if you have not any reference in this case. Compair the following codes with your code. I tested it. It works...
Note1: You should use base in your constructor to pass name and basepay to their corresponding fields in base class.
Note2: Now Rebuild your project, have you any error? I have not! Have you VS Intellisense problem yet?
I have 3 methods.
1 method holding the value of 3000
1 method holding the value of 0.13
and I have created another method that I want to multiply these two figures together.
public override int FishPerTank()
{
return 3000;
}
public override double WeightOut(double weightOut, double weightIn)
{
return 0.13;
}
public override int HowMuchTheFishWeighOutKG()
{
return (FishPerTank() * WeightOut());
}
I am receiving the syntax error on the WeightOut here:
public override int HowMuchTheFishWeighOutKG()
{
return (FishPerTank() * WeightOut());
}
WeightOut expect 2 parameters and you're not providing them
WeightOut(double weightOut, double weightIn) is declared with two parameters and you're calling it with none. Hence the error.
WeightOut()
expects two parameters. But why ? You don't use them.
Rewrite your method without the 2 parameters
public double WeightOut()
{
return 0.13;
}
You probably want to change
public override double WeightOut(double weightOut, double weightIn)
{
return 0.13;
}
to
public override double WeightOut()
{
return 0.13;
}
as you aren't using the parameters.
also why the override? May need to remove that if removing the parameters causes another syntax error, or fix it in the base class as well.