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.
Related
Is it possible to create a class that has a method definition where the method can be accessed statically, and also be accessed via an instance of the class, without having to have two separate names for the method or a separate set of arguments to distinguish the methods as two different methods.
i.e.
public class MyClass
{
public static int GetMyInt()
{
return 1;
}
}
...
MyClass classInst = new MyClass();
int i = MyClass.GetMyInt();
int x = classInst.GetMyInt();
Is this possible in C#? If so, how so?
No. A method is static or is not.
I don't a valid use case you want to allow calling a static method against an instance of a class.
I dont think you can have the cake and eat the cake too.
Static (methods which are called through class) and non-static (methods which are called through instance of class ) are two opposite sides of a coin.
So either it is static or non-static but not both
A static (or class) method is by definition different from an instance method.
An instance method is only accessible when you create an instance of that class;
A static method is always accessible, since it doesn't require class instanciation (provided it is public), at least always accessible within the class itself. You should know, however, that if you have a static variable, any changes made to that variable will affect the class, and have an impact everywhere that variable is used on the application.
eg.
...
static int lastId;
public static int getLastId(){
return lastId++;
}
This is a way you may control an autonumber on a class, since whenever you call getLastId, lastId will be incremented and that is valid for all the application.
edit
the sample code illustrates what happens with a static variable. That said, you should know that overloading is supported on c#. What you cannot have is a pair of methods with the same name tag and the same set and type of parameters.
for eg., this builds ok.
public static int getValue()
{
return 1;
}
public int getValue(int x)
{
return x * 1;
}
but this will throw an error:
public static int getValue(int z)
{
return 1;
}
public int getValue(int x)
{
return x * 1;
}
that is true independently of wether there is a static method or not. This will also generate a compile time error:
public int getValue(int z)
{
return 1;
}
public int getValue(int x)
{
return x * 1;
}
even this will give you an error:
public string getValue(int z)
{
return 1;
}
public int getValue(int x)
{
return x * 1;
}
so, yes, you may have a static method with the same name tag of an instance method, but you may not have the same set and type of parameters.
If you want both static an instance methods to have the same behaviour, then why do you need the intance method really? The static method will do the trick (considering you know the consequences of having a static method and its implications).
Nope. But you can wrap it. But will have to give it a new signature.
public int getMyInt()
{
return GetMyInt();
}
I have the following code:
private double Input1
{
get
{
double x;
return double.TryParse(Input1TextBox.Text, out x) ?
x * (Prefix1ComboBox.SelectedItem as MetricPrefix).Multiplier : double.NaN;
}
}
I was wondering if there's anyway to omit the variable declaration and get this all on one line, or if this is the only possible way.
You can create your own Util class with custom TryParse which would return double? instead:
public static class Util
{
public static double? TryParse(string source)
{
double x;
if (double.TryParse(source, out x))
return x;
return null;
}
}
and then use it:
return (Util.TryParse(Input1TextBox.Text) ?? double.NaN) * (Prefix1ComboBox.SelectedItem as MetricPrefix).Multiplier;
It uses the fact that double.NaN multiplied by other number gives NaN as well.
Unfortunately, no. However, is this a major problem? You can mask this by creating an extension method to do it for you though, if it's not aesthetically pleasing:
get
{
return Input1TextBox.Text.ConvertTo<double>(double.Nan);
}
And implement the extension method there to do the defaulting.
This is the only possible way, unless you decide to cheat by making x a class member instead of a local. Or if you decide to cheat by hiding everything inside another method.
There is no real benefit in cutting down the number of newlines though.
No you need to declare the variable first to use TryParse.
It can as of 2021 in C#7 (possible earlier, unconfirmed), using modern notation.
class MainForm
{
//...
private double Input1 =>
double.TryParse(Input1TextBox.Text, out double x) ? x * (Prefix1Combo.SelectedItem as MetricPrefix).Multiplier : double.NaN;
//...
}
You simply denote the type (double in this example) along with the out parameter modifier, which will effectively create a local variable of the name passed in the parameter modifier to be used anywhere in the code AFTER called, in-line.
Note that the type could also be inferred with var instead of the type, and the legacy notation which is more along the lines of how it was originally written:
class MainForm
{
//...
private double Input1
{
return double.TryParse(Input1TextBox.Text, out var x) ?
x * (Prefix1ComboBox.SelectedItem as MetricPrefix).Multiplier : double.NaN;
}
//...
}
I have a basic class with this method including
public class Account
{
//MEMBERS
private int acctNo;
protected double balance;
public double deposit;
// CONSTRUCTORS
public Account() //member intitilization
{
acctNo = 54534190;
balance = 7500;
deposit= 1500;
}
//PROPERTIES
public int AcctNo
{
get {return acctNo; }
set {acctNo = value; }
}
public double Balance
{
get { return balance; }
set { balance = value; }
}
public double Deposit
{
get {return deposit; }
set {deposit = value; }
}
public virtual double getDeposit (double amount)
{
double transactionAmt=0.00;
if (amount>0)
{
balance+=amount;
transactionAmt= amount;
}
return transactionAmt;
}
Now in my actual program I am trying to output this method. What would my writeline look like?
I tried to write this:
static void Main(string[] args)
{
Console.WriteLine("CREATING ACCOUNT");
Account myAcctDefault = new Account();
DumpContents(myAcctDefault);
Pause();
}
static void DumpContents(Account account)
{
Console.WriteLine(" output {0}", account.getDeposit());
}
I am getting an error saying:
no overload for method 'getDeposit' takes 0 arguments.
What am I doing wrong, am I trying to output this method incorrect?
Any help, insight or suggestions would be extremely helpful.
I am new to c# as I'm sure you can tell. What is the proper process to output a method in this context?
I am getting an error saying "no overload for method 'getDeposit' takes 0 arguments". What am I doing wrong
Exactly what it says. Here's your method call:
Console.WriteLine(" output {0}", account.getDeposit());
... and here's the method declaration:
public virtual double getDeposit (double amount)
Note how the method declares a parameter - but you're not providing an argument. Either you need to get rid of the parameter, or you need to add an argument to the method call. Or you need to change to using a different method - one which doesn't change the balance of the account. (It seems unlikely that you want to do that in this case.) Perhaps you should add a Balance property:
// Please note that this should probably be decimal - see below
public double Balance { get { return balance; } }
Then call it with:
Console.WriteLine(" output {0}", account.Balance);
Additionally:
For financial quantities, it's generally better to use decimal than double. Read my articles on decimal floating point and binary floating point for more information.
Your getDeposit method doesn't follow .NET naming conventions, where (at least public) methods are named in PascalCase, with a leading capital letter
Your getDeposit method is oddly named as it isn't "getting" a deposit - it's making a deposit (and returning the balance)
Your getDeposit method always returns the value passed into it, unless it's negative. That seems odd to me - if it's going to return anything, shouldn't it return the balance?
Your getDeposit method silently ignores negative deposits. I'd expect this to throw an error, as trying to make a negative deposit indicates a programming error IMO.
Your getDeposit method takes one argument that you are not passing to it. Depends what you want to achieve either pass a value to method:
static void DumpContents(Account account)
{
double deposit = 1000;
Console.WriteLine(" output {0}", account.getDeposit(deposit));
}
or remove this argumentparameter from the method signature.
//You have to pass a double value into the method, because there is only one method
//and wants a double paramater:
//this is what you created:
public double getDeposit(double amount) // <-
{
double transactionAmt = 0.00;
if (amount > 0)
{
balance += amount;
transactionAmt = amount;
}
return transactionAmt;
}
//This how you should call it:
static void DumpContents(Account account)
{
Console.WriteLine(" output {0}", account.getDeposit(34.90)); //<-
}
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()
{
...
}
Im trying to use this method called GetDouble but i keep getting the error "no overload for method 'GetDouble' takes 1 arguments" and i have no idea how to fix it.
public static bool GetDouble(string StringToConvert, out double dblOutValue)
{
return double.TryParse(StringToConvert, out dblOutValue);
}
im calling it from this method
private bool ReadAndValidatePrice(out double price)
{
price = 0.0;
if (!InputUtility.GetDouble(txtPrice.Text))
{
}
}
Any help trying to fix it is appriciated, thanks.
As the error is trying to tell you, GetDouble() takes two arguments.
The second argument is an out parameter, meaning that it will set the variable you pass to it as a result.
When calling it, you must pass a variable with the out keyword.
You have a few issues here. The first is your GetDouble method. What are you trying to do? If you are trying to just get the double (as the name implies) then it should be more like
public static double GetDouble(string StringToConvert)
{
double dblOutValue;
double.TryParse(StringToConvert, out dblOutValue);
return dblOutValue;
}
Then look at your ReadandValidatePrice method. With the above change it should be more like:
private bool ReadAndValidatePrice(out double price)
{
price = InputUtility.GetDouble(txtPrice.Text)
//not sure if the IF statement is needed anymore so it is omitted
}
How is that? Where my assumptions completely wrong?
You miss one parameter ,GetDouble() takes two parameters. But you have pass one parameter, So you got that error . Now try below method instead of your method .
private bool ReadAndValidatePrice(out double price)
{
price = 0.0;
if (!InputUtility.GetDouble(txtPrice.Text, out price ))
{
}
}
Your method should look like follow, because your GetDouble() method defines two parameter:
private bool ReadAndValidatePrice(out double price)
{
price = 0.0;
if (!InputUtility.GetDouble(txtPrice.Text, out price))
{
}
}