Operator '*' cannot be applied to operands of type 'object' and 'object' - c#

I have the following code which gives a warning
Operator '*' cannot be applied to operands of type 'object' and 'object'
protected void Submitbtn_Click(object sender, EventArgs e)
{
txtTotal1.Text = Nz(txtbox1.Text, 0) * Nz(Label1.Text, 0);
txtTotal2.Text = Nz(txtbox2.Text, 0) * Nz(Label2.Text, 0);
txtTotal3.Text = Nz(txtbox3.Text, 0) * Nz(Label3.Text, 0);
txtTotal4.Text = Nz(txtbox4.Text, 0) * Nz(Label4.Text, 0);
txtTotal5.Text = Nz(txtbox5.Text, 0) * Nz(Label5.Text, 0);
txtTotal6.Text = Nz(txtbox6.Text, 0) * Nz(Label6.Text, 0);
}
public object Nz(object Value, object MyDefault = "")
{
if (Value == null || Information.IsDBNull(Value) || Value == "")
return MyDefault;
else
return Value;
}
}
Can someone explain to me why i'm getting error in my code and a solution to fix the error

Related

TextToSplit does not exist in current context

Am giving to 2 variables the data type as string and integer.
However C# is saying that they don't exist.
Have tried something as object TexttoSplit { get; private set; } but still doesn't run correctly.
Any help would be much appreciated!
private static List<string> SplitTextByLengthEngine(string Texttosplit, int MaxLineLength)
{
List<string> RetVal = new List<string>();
MaxLineLength = Math.Min(MaxLineLength, TexttoSplit.Length);
int LastIndex = TexttoSplit.Substring(0, Math.Min((MaxLineLength + 1), TextToSplit.Length)).LastIndexOf(" ");
if (((TextToSplit.Length <= MaxLineLength)
|| (LastIndex == -1)))
{
RetVal.Add(TexttoSplit.Substring(0, MaxLineLength));
string RemainingText = TexttoSplit.SubString(MaxLineLength, (TextToSplit.Length - MaxLineLength)).Trim();
}
if ((RemainingText.Length > 0))
{
RetVal.AddRange(SplitTextByLengthEngine(RemainingText, MaxLineLength));
}
else
{
// Track backwards to find previous non-space character
int Index = (LastIndex - 1);
while (((Index >= 0)
&& (TextToSplit.SubString(Index, 1) == " ")))
{
Index--;
}
if ((Index >= 0))
{
RetVal.Add(TextToSplit.SubString(0, (Index + 1)));
string RemainingText = TexttoSplit.SubString((Index + 1), (TextToSplit.Length
- (Index + 1))).Trim();
}
if ((RemainingText.Length > 0))
{
RetVal.AddRange(SplitTextByLengthEngine(RemainingText, MaxLineLength));
}
return RetVal;
}
}
The method argument is called Texttosplit
In the method body you refer to TextToSplit
Note the difference in upper/lowercase

c# Cannot implicitly convert type 'double' to System.Window.Forms.Textbox

I have this error code "Cannot implicitly convert type 'double' to System.Window.Forms.Textbox" and i'm not sure why i'm getting it. If some one could exlpain it it would be great and give me ideas on how to fix it please. I have looked at other post but still can not work it out.
Thank you for your help
int SumOfSquares(int txtSide1, int txtSide2)
{
txtSide1 *= txtSide1;
txtSide2 *= txtSide2;
return txtSide1 + txtSide2;
}
private void btnCalculate_Click(object sender, EventArgs e)
{
int Side1 = int.Parse(txtSide1.Text);
int Side2 = int.Parse(txtSide2.Text);
int SumLessOne = SumOfSquares(Side1, Side2) - 1;
if (SumOfSquares(Side1, Side2) > 50)
{
txtHypotenuse.Text = "Overflow";
}
else
{
txtHypotenuse.Text = "Safe";
}
txtHypotenuse.Text = Math.Sqrt(SumOfSquares(Side1 , Side2)); // this is the line the error is on
}
}
Add ToString()
txtHypotenuse.Text = Math.Sqrt(SumOfSquares(Side1 , Side2)).ToString();
txtHypotenuse.Text = Convert.ToString(Math.Sqrt(SumOfSquares(Side1 , Side2)));

Possible unintended reference comparison in C#

I am getting an Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string' on the if statements in the GetPrice method. It shows its highlighted on all the "if (size == "Small")" statements. Here are my variables:
drinkType = GetDrinkType();
size = GetDrinkSize();
price = GetPrice(size);
private string GetDrinkType()
{
string theDrink;
theDrink = "None Selected";
if (rdoCoffee.Checked)
{
theDrink = "Coffee";
}
else if (rdoCoco.Checked)
{
theDrink = "Hot Chocolate";
}
else if (rdoSmoothie.Checked)
{
theDrink = "Smoothie";
}
return theDrink;
}
private string GetDrinkSize()
{
string theSize;
theSize = "None Selected";
if (rdoSmall.Checked)
{
theSize = "Small";
}
else if (rdoMedium.Checked)
{
theSize = "Medium";
}
else if (rdoLarge.Checked)
{
theSize = "Large";
}
return theSize;
}
private decimal GetPrice(object size)
{
decimal thePrice;
thePrice = 0;
if (size == "Small")
{
thePrice = 1.25m;
}
else if (size == "Medium")
{
thePrice = 2.50m;
}
else if (size == "Large")
{
thePrice = 3.35m;
}
return thePrice;
}
The size parameter is declared of type object, so the compiler doesn't know it's actually of type string. So it uses the default equality for type object, which is a reference comparison.
If you change the type of size to string, it will use the equality operator overload from the string class, which performs a value comparison.
private decimal GetPrice(string size)
The warning occurs because you are comparing a string to an object. If you change
if (size == "Small")
to
if (size.ToString() == "Small")
the warning will be removed.
Try changing the "object" in GetPrice to "string".
Since in GetPrize, the type of size is object, but you are comparing it to a string with size == "Large".
Change the comparison with "string text".Equals(object) as shown below
private decimal GetPrice(object size)
{
decimal thePrice = 0m;
if ("Small".Equals(size))
{
thePrice = 1.25m;
}
else if ("Medium".Equals(size))
{
thePrice = 2.50m;
}
else if ("Large".Equals(size))
{
thePrice = 3.35m;
}
return thePrice;
}

Why is this dynamic list comparison failing?

I have a search that returns a result that is dynamic. So I am trying to just show a label if there are no results found. The problem i am having is i dont know how to count the result because it is dynamic and is not equal to a type.
The error message is :
Operator '!=' Cannot be applied ot operands of type
System.Collections.Generic.List and int
if (Page.IsValid)
{
string keyword = txtSearch.Text.Trim();
List<dynamic> results = SearchItems(keyword);
List<dynamic> Cresults = SearchContacts(keyword);
if(results != 0 || Cresults !=0)
{
//bind and return
LVI.DataSource = results;
LVI.DataBind();
// System.Threading.Thread.Sleep(500);
//Contact Bind return
LVC.DataSource = Cresults;
LVC.DataBind();
// System.Threading.Thread.Sleep(250);
lvAdmin.DataSource = results;
lvAdmin.DataBind();
LVCAdmin.DataSource = Cresults;
LVCAdmin.DataBind();
}
else{
NoResults.Visible = true;
}
You cannot just do:
if(results != 0 || Cresults !=0)
{
}
That way your comparing the actual List to 0, which obviously fails.
Just do:
if(results.Count != 0 || Cresults.Count !=0)
{
}
Or:
if(results.Any() || Cresults.Any())
{
}
Use the Count property of the List class:
if (results.Count != 0 || Cresults.Count != 0)
{
//rest of code
}
Docs: http://msdn.microsoft.com/en-us/library/a7f69ad7.aspx
you can try using count
if(results.Count > 0 || Cresults.Count > 0)

Nullable Property throwing NullReferenceException on .HasValue

This line of (C#) code
if (!currentLap.S1.HasValue)
is giving me
System.NullReferenceException: Object reference not set to an instance of an object.
provided I'm sure that currentLap variable is instantiated (because it's being used a few lines before and it is a local variable) and it has following property:
private double? _s1;
[DefaultValue(null)]
[JsonConverter(typeof(ShortDoubleConverter))]
public double? S1
{
get { return _s1; }
set { _s1 = value; }
}
how can it possibly throw NullReferenceException? Can it be something to do with optimization on Release mode?
Thanks,
Stevo
EDIT:
here is full method code.
public void Update(DriverData driverData)
{
LapInfo currentLap = this.CurrentLap;
if (currentLap != null &&
this.LastDriverData != null &&
driverData.TotalLaps != this.LastDriverData.TotalLaps &&
driverData.InPits &&
driverData.Speed < 10 &&
!this.LastDriverData.InPits)
{
currentLap.Escaped = true;
}
this.LastDriverData = driverData;
if ((currentLap == null || currentLap.Lap != driverData.LapNumber) &&
!this.Laps.TryGetValue(driverData.LapNumber, out currentLap))
{
currentLap = new LapInfo() { Lap = driverData.LapNumber, Parent = this, Class = driverData.Class };
this.Laps.Add(driverData.LapNumber, currentLap);
int lapsCount = 0, completedDriverLaps = 0, cleanLaps = 0;
this.TotalLaps = driverData.TotalLaps;
//if it's not the first lap
if (driverData.TotalLaps > 0)
{
//previous lap
if (this.CurrentLap == null || !this.CurrentLap.Escaped)
{
this.CompletedLaps++;
if (this.CurrentLap == null || !this.CurrentLap.MaxIncident.HasValue)
this.CleanLaps++;
}
}
foreach (DriverLapsInfo laps in this.Parent.LapsByVehicle.Values)
{
lapsCount += laps.TotalLaps;
completedDriverLaps += laps.CompletedLaps;
cleanLaps += laps.CleanLaps;
}
this.Parent.Parent.SetLapsCount(driverData, lapsCount, driverData.Class, completedDriverLaps, cleanLaps);
}
this.CurrentLap = currentLap;
//add incidents
if (driverData.Incidents != null)
{
foreach (IncidentScore incident in driverData.Incidents)
{
this.CurrentLap.MaxIncident = Math.Max(this.CurrentLap.MaxIncident ?? 0, incident.Strength);
this.CurrentLap.Incidents++;
this.Incidents++;
}
}
LapInfo previousLap = null;
if ((this.PreviousLap == null || this.PreviousLap.Lap != driverData.TotalLaps) &&
this.Laps.TryGetValue(driverData.TotalLaps, out previousLap))
{
this.PreviousLap = previousLap;
if (!this.PreviousLap.Date.HasValue)
{
this.PreviousLap.Date = DateTime.UtcNow;
}
}
if (currentLap.Position == 0)
currentLap.Position = driverData.Position;
if (driverData.CurrentS1 > 0)
{
**if (!currentLap.S1.HasValue)**
{
this.UpdateBestS1(driverData.BestS1);
this.Parent.Parent.UpdateBestS1(driverData.BestS1, driverData.UniqueName);
currentLap.UpdateS1(driverData.CurrentS1, driverData);
//reset the best split set at the finish line
if (this.PreviousLap != null && this.PreviousLap.SplitBest < 0)
this.PreviousLap.SplitBest = 0;
}
if (driverData.CurrentS2.HasValue && driverData.CurrentS1.HasValue && !currentLap.S2.HasValue)
{
double s2 = driverData.CurrentS2.Value - driverData.CurrentS1.Value;
this.UpdateBestS2(s2);
this.Parent.Parent.UpdateBestS2(s2, driverData.UniqueName);
currentLap.UpdateS2(s2, driverData);
}
}
if (this.PreviousLap != null)
{
if (driverData.LastLap > 0)
{
if (!this.PreviousLap.S3.HasValue && driverData.LastS2.HasValue)
{
double s3 = driverData.LastLap.Value - driverData.LastS2.Value;
this.UpdateBestS3(s3);
this.Parent.Parent.UpdateBestS3(s3, driverData.UniqueName);
this.PreviousLap.UpdateS3(s3, driverData);
}
if (!this.PreviousLap.LapTime.HasValue)
{
double? bestLap = this.Parent.Parent.BestLap;
this.PreviousLap.UpdateLapTime(driverData, 0);
this.Parent.Parent.UpdateBestLap(this.PreviousLap, driverData.BestLap, driverData);
this.UpdateBestLap(driverData.BestLap, this.PreviousLap);
this.PreviousLap.UpdateLapTime(driverData, bestLap);
}
}
else
{
if (this.PreviousLap.SplitBest.HasValue)
this.PreviousLap.UpdateBestSplit();
if (this.PreviousLap.SplitSelf.HasValue)
this.PreviousLap.UpdateSelfSplit();
}
}
if (driverData.InPits)
{
switch (driverData.Sector)
{
case Sectors.Sector1:
if (previousLap != null)
previousLap.InPits = true;
break;
case Sectors.Sector3:
currentLap.InPits = true;
break;
}
}
//lap to speed
if (currentLap.TopSpeed < driverData.Speed)
{
driverData.TopSpeedLap = driverData.Speed;
currentLap.UpdateTopSpeed(driverData.Speed);
}
else
driverData.TopSpeedLap = currentLap.TopSpeed;
//overall top speed
if (this.TopSpeed < driverData.Speed)
{
driverData.TopSpeed = driverData.Speed;
this.TopSpeed = driverData.Speed;
this.Parent.Parent.UpdateTopSpeed(this.TopSpeed, driverData);
}
else
driverData.TopSpeed = this.TopSpeed;
}
There is no way on earth the code can make it to that line and currentLap beeing null.
Or am I going crazy? :)
.HasValue will not throw if the nullable reference is null, but a.b.HasValue will if a is null.
I suspect that currentLap == null. I know you say you're sure that currentLap is not null, but I think that's the most likely explanation. Can you post more code?
Update:
Thanks for posting your code.
This doesn't throw:
void Main() {
var f = new Foo();
Console.WriteLine (f.S1);
Console.WriteLine (f.S1.HasValue);
}
class Foo {
private double? _s1 = null;
public double? S1 {
get { return _s1; }
set { _s1 = value; }
}
}
Could you try to create a minimal reproduction? (minimal code that exhibits the issue)
Maybe have a look at the previous line of code :) - debugger often highlights the next line after the one where the NullReferenceException was actually thrown.

Categories

Resources