Variable Not holding values - c#

I'm having an issue with a program I am trying to create. This program is like a credit card and the issue is that the amount of money I put in the 'Credit' variable doesn't seem to affect the variable at all, it stays empty.
The following is the Credit Card class:
I have edited the code because I have just noticed I did not insert everything and have also included the program.cs! The outcome of this program when it runs: https://prnt.sc/jynpt1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreditCardExample
{
public class CreditCard
{
private double credit;
public double Credit
{
get { return credit; }
set { credit = value; }
}
public CreditCard(double credit)
{
this.credit = Credit;
}
public bool enoughCredit (double creditAmt)
{
bool state = false;
if (Credit >= creditAmt)
{
Console.WriteLine("You have sufficient funds.");
state = true;
}
else
{
Console.WriteLine("You do not have sufficient amount");
state = false;
}
return state;
}
public double getAmtInCreditCard()
{
Console.WriteLine("Amount of Money in your CreditCard: ", Credit);
return Credit;
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreditCardExample
{
class Program
{
static void Main(string[] args)
{
CreditCardExample.CreditCard c = new
CreditCardExample.CreditCard(20.0);
c.enoughCredit(12);
c.getAmtInCreditCard();
Console.ReadKey();
}
}
}

That's because in your constructor you are assigning the property back to itself and not the value being passed i.e.
this.credit = Credit // notice the casing?
Change to
this.credit = credit;

You have a bug in your code.
public CreditCard(double credit)
{
Credit = credit;
}
Test:
class CreditCard
{
private double credit;
public double Credit
{
get { return credit; }
set { credit = value; }
}
public CreditCard(double credit)
{
Credit = credit;
}
}
static void Main()
{
//Outputs "10"
Console.WriteLine(new CreditCard(10).Credit);
}

Related

Missing bracket in C# because of Windows IoT background task?

I have created a test app for my first Windows IoT project with raspberry pi and an ultrasonic sensor.
I have placed some sample code in it. Visual Studio tells me that I am missing a curly bracket in "public void run…", but that doesn't seem to be the problem.
Is it because of the public class within the BackgroundTaskInstance?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using Windows.ApplicationModel.Background;
using Windows.Devices.Gpio;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
// The Background Application template is documented at http://go.microsoft.com/fwlink/?LinkID=533884&clcid=0x409
namespace IoTtest
{
public sealed class StartupTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
public class HCSR04
{
private GpioPin triggerPin { get; set; }
private GpioPin echoPin { get; set; }
private Stopwatch timeWatcher;
public HCSR04(int triggerPin, int echoPin)
{
GpioController controller = GpioController.GetDefault();
timeWatcher = new Stopwatch();
//initialize trigger pin.
this.triggerPin = controller.OpenPin(triggerPin);
this.triggerPin.SetDriveMode(GpioPinDriveMode.Output);
this.triggerPin.Write(GpioPinValue.Low);
//initialize echo pin.
this.echoPin = controller.OpenPin(echoPin);
this.echoPin.SetDriveMode(GpioPinDriveMode.Input);
}
public double GetDistance()
{
ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne(500);
timeWatcher.Reset();
//Send pulse
this.triggerPin.Write(GpioPinValue.High);
mre.WaitOne(TimeSpan.FromMilliseconds(0.01));
this.triggerPin.Write(GpioPinValue.Low);
return this.PulseIn(echoPin, GpioPinValue.High);
}
private double PulseIn(GpioPin echoPin, GpioPinValue value)
{
var t = Task.Run(() =>
{
//Recieve pusle
while (this.echoPin.Read() != value)
{
}
timeWatcher.Start();
while (this.echoPin.Read() == value)
{
}
timeWatcher.Stop();
//Calculating distance
double distance = timeWatcher.Elapsed.TotalSeconds * 17000;
return distance;
});
bool didComplete = t.Wait(TimeSpan.FromMilliseconds(100));
if (didComplete)
{
return t.Result;
}
else
{
return 0.0;
}
}
}
}
}
I took the code and reformatted it for you. Please change the namespace to the value you would like
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace MyIotNamespace
{
public sealed class StartupTask :IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
}
}
public class HCSR04
{
private GpioPin triggerPin { get; set; }
private GpioPin echoPin { get; set; }
private Stopwatch timeWatcher;
public HCSR04(int triggerPin, int echoPin)
{
GpioController controller = GpioController.GetDefault();
timeWatcher = new Stopwatch();
//initialize trigger pin.
this.triggerPin = controller.OpenPin(triggerPin);
this.triggerPin.SetDriveMode(GpioPinDriveMode.Output);
this.triggerPin.Write(GpioPinValue.Low);
//initialize echo pin.
this.echoPin = controller.OpenPin(echoPin);
this.echoPin.SetDriveMode(GpioPinDriveMode.Input);
}
public double GetDistance()
{
ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne(500);
timeWatcher.Reset();
//Send pulse
this.triggerPin.Write(GpioPinValue.High);
mre.WaitOne(TimeSpan.FromMilliseconds(0.01));
this.triggerPin.Write(GpioPinValue.Low);
return this.PulseIn(echoPin, GpioPinValue.High);
}
private double PulseIn(GpioPin echoPin, GpioPinValue value)
{
var t = Task.Run(() =>
{
//Recieve pusle
while(this.echoPin.Read() != value)
{
}
timeWatcher.Start();
while(this.echoPin.Read() == value)
{
}
timeWatcher.Stop();
//Calculating distance
double distance = timeWatcher.Elapsed.TotalSeconds * 17000;
return distance;
});
bool didComplete = t.Wait(TimeSpan.FromMilliseconds(100));
if(didComplete)
{
return t.Result;
}
else
{
return 0.0;
}
}
}
}
Nested class can't exist inside functions. Place HCSR04 inside StartupTask instead.
See https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/nested-types

Converting vb to c# code

Could you help me here, this is my friend's work(actually don't know where did he get this code, it uses vb language) and i'm trying to convert the code to c#. Thought it was easy, even though i lack of c# knowledge, and i'm stacked from here. I found a vb.net to c# converter from the net, and this is the result:
*see the comment below
clsProcess.cs:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
[Serializable()]
public class clsProcess : IComparable<clsProcess>
{
public int Priority
{
get { return _Priority; }
set { _Priority = value; }
}
public Color ProcessColor
{
get { return _ProcessColor; }
set { _ProcessColor = value; }
}
public double ArrTime
{
get { return _ArrTime; }
set { _ArrTime = value; }
}
public double ExeTime
{
get { return _ExeTime; }
set { _ExeTime = value; }
}
public string Label
{
get { return _Label; }
set { _Label = value; }
}
public clsProcess()
{
}
public clsProcess(int prior, double arr, double exe, string lbl, Color clr)
{
_Priority = prior;
_ArrTime = arr;
_ExeTime = exe;
_Label = lbl;
_ProcessColor = clr;
}
private double _ArrTime;
private double _ExeTime;
private string _Label;
private int _Priority;
private Color _ProcessColor;
public int CompareTo(clsProcess other)
{
switch ((modGlobals.SortColumn))
{
//The method SortType from modGlobals.cs is the error.
//Error says: The name 'SortType' does not exist in the current context
//I'm getting error from here:
case SortType.Arr:
return this.ArrTime.CompareTo(other.ArrTime);
case SortType.Exe:
return this.ExeTime.CompareTo(other.ExeTime);
case SortType.Label:
return this.Label.CompareTo(other.Label);
case SortType.Prior:
return this.Priority.CompareTo(other.Priority);
//Until here.
}
}
}
modGlobals.cs:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
static class modGlobals
{
public enum SortType //The error referring to.
{
Arr,
Exe,
Prior,
Label
}
public static SortType SortColumn; //I doubt it has something to do here.
public static List<clsProcess> CreateMemberwiseClone(List<clsProcess> pList)
{
List<clsProcess> tempList = new List<clsProcess>();
int i = 0;
for (i = 0; i <= pList.Count - 1; i++) {
tempList.Add(CloneProcess(pList[i]));
}
return tempList;
}
public static clsProcess CloneProcess(clsProcess process)
{
clsProcess temp = new clsProcess();
temp.ExeTime = process.ExeTime;
temp.ArrTime = process.ArrTime;
temp.Label = process.Label;
temp.Priority = process.Priority;
temp.ProcessColor = process.ProcessColor;
return temp;
}
public static void MergeBlocks(ref List<clsBlock> blocks)
{
if (blocks.Count < 2)
return;
int i = 0;
while (i < blocks.Count - 1) {
if (blocks[i].BlockCaption == blocks[i + 1].BlockCaption) {
blocks[i].BlockLength += blocks[i + 1].BlockLength;
blocks.RemoveAt(i + 1);
i -= 1;
}
i += 1;
}
}
}
Could you give me an alternate solution for here?
try
public int CompareTo(clsProcess other)
{
switch ((modGlobals.SortColumn))
{
case modGlobals.SortType.Arr:
return this.ArrTime.CompareTo(other.ArrTime);
case modGlobals.SortType.Exe:
return this.ExeTime.CompareTo(other.ExeTime);
case modGlobals.SortType.Label:
return this.Label.CompareTo(other.Label);
case modGlobals.SortType.Prior:
return this.Priority.CompareTo(other.Priority);
}
//This next part will happen if the switch statement doesnt find a match
//use this to return some default value or a value that tells you it didnt find something
//I'll use 0 as an example
return 0;
//now all paths return a value, even if it doesnt find a match in the switch statement
}
Your static class modGlobals should only have static members.
The SortType should be static.
public static enum SortType
{
Arr,
Exe,
Prior,
Label
}

Property or indexer must have at least one accessor

I'm learning C#, trying to get to grips with accessors at the moment.
I'm going nuts looking at this, I have no idea what I've done wrong:
class BankAccount
{
// *PROPERTIES*
private int _initialDeposit = 0;
// **ACCESSORS**
public int SavingsAccount
{
set
{
_initialDeposit = value;
}
get
{
return _initialDeposit;
}
}
}
The Form looks like this:
public partial class BankForm : Form
{
private BankAccount _myAccount;
public BankForm()
{
InitializeComponent();
_myAccount = new BankAccount();
}
private void initialDepositButton_Click(object sender, EventArgs e)
{
_myAccount.SavingsAccount = Convert.ToInt32(initialDepositTextBox.Text);
bankAccountListBox.Text = "Account opened with initial Deposit " + initialDepositTextBox.Text;
}
}
But I get this error:
Property or indexer must have at least one accessor
I'm not getting any errors. Move location of private BankAccount _myAccount;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BankForm
{
public partial class BankForm : Form
{
public BankForm()
{
InitializeComponent();
_myAccount = new BankAccount();
}
private BankAccount _myAccount;
private void initialDepositButton_Click(object sender, EventArgs e)
{
_myAccount.SavingsAccount = Convert.ToInt32(initialDepositTextBox.Text);
bankAccountListBox.Text = "Account opened with initial Deposit " + initialDepositTextBox.Text;
}
}
class BankAccount
{
// *PROPERTIES*
private int _initialDeposit = 0;
// **ACCESSORS**
public int SavingsAccount
{
set
{
_initialDeposit = value;
}
get
{
return _initialDeposit;
}
}
}
}
​

Web User Control Collection data is not storing

I wanted to create a web control which has collection featured in the ASPX. I have code below which has a problem.
I seem to turn off and objects collection editor(collection stable).But I object design information Design Time at runtime what you can not get
when I turn off the project.So in a way the information will be saved during design is disappear.
When I open the project files in aspx file nor what. Designer.cs do not coincide in any record in the file.
I want to show in the picture below, this situation partially.
Based on the above, or as seen in the example in asp.net collection listing on sample collection can fix or waiting for your advice.
Here is code
//******************************************************Rol.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SANNET.ToolBox.TemelRoller
{/*
[ControlBuilder(typeof(ListItemControlBuilder))]
[ParseChildren(true, "Text")]*/
[TypeConverter(typeof(ExpandableObjectConverter))]
public class Rol
{
private string rolAdi;
private AksiyonTuru aksiyonIcinKullan;
private EfektTuru iseYapilacak;
private string hataMesaji;
private IOzelEfekt ozelEfekt;
public String RolAdi { get { return rolAdi; } set { rolAdi = value; } }
public AksiyonTuru AksiyonIcinKullan { get { return aksiyonIcinKullan; } set { aksiyonIcinKullan = value; } }
public EfektTuru IseYapilacak { get { return iseYapilacak; } set { iseYapilacak = value; } }
public String HataMesaji { get { return hataMesaji; } set { hataMesaji = value; } }
public IOzelEfekt OzelEfekt { get { return ozelEfekt; } set { ozelEfekt = value; } }
public Rol()
{
RolAdi = "Hicbiri";
}
/*
public string GetAttribute(string key)
{
return (String)ViewState[key];
}
public void SetAttribute(string key, string value)
{
ViewState[key] = value;
}*/
}
}
//******************************************************RolListesi.cs
using SANNET.ToolBox.Yardimcilar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web.UI;
namespace SANNET.ToolBox.TemelRoller
{
//[TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))]
[TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))]
public class RolListesi : CollectionBase//ICollection<Rol>
{
private Collection<Rol> roller;
private Control parent;
public RolListesi(Control parent)
{
this.parent = parent;
parent.PreRender += parent_PreRender;
parent.Load += parent_PreRender;
roller = new Collection<Rol>();
}
void parent_PreRender(object sender, EventArgs e)
{
RolIslemleri.PreRenderIsle((Control)sender, this);
}
public Control Parent { get { return this.parent; } }
public Rol rolGetir(String rolAdi)
{
foreach (Rol r in roller) {
if (r.RolAdi.Equals(rolAdi))
return r;
}
return null;
}
public bool Contains(String rolAdi)
{
return rolGetir(rolAdi) != null;
}
public Rol this[int index]
{
get { return (Rol)roller[index]; }
}
public void Add(Rol emp)
{
roller.Add(emp);
}
public void Remove(Rol emp)
{
roller.Remove(emp);
}
}
}
//******************************************************RolCollectionEditor.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SANNET.ToolBox.TemelRoller
{
public class RolCollectionEditor : CollectionEditor
{
public RolCollectionEditor(Type type)
: base(type)
{
}
protected override string GetDisplayText(object value)
{
Rol item = new Rol();
item = (Rol)value;
return base.GetDisplayText(string.Format("{0}, {1}", item.RolAdi,
item.AksiyonIcinKullan));
}
}
}
//******************************************************SANButton.cs
using DevExpress.Web.ASPxEditors;
using SANNET.ToolBox.TemelRoller;
using System.ComponentModel;
using System.Web.UI;
namespace SANNET.ToolBox.Bilesenler
{
public class SANButton : ASPxButton, IRolSahibi
{
private RolListesi roller;
/* [Editor(typeof(System.ComponentModel.Design.CollectionEditor),
typeof(System.Drawing.Design.UITypeEditor))]*/
[Editor(typeof(RolCollectionEditor),
typeof(System.Drawing.Design.UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public RolListesi Roller { get {
if (roller == null)
{
roller = new RolListesi(this);
}
return roller; } }
}
}
The answer is
[PersistenceMode(PersistenceMode.InnerProperty)]
Here is sample usage
private Roller roller;
[Editor(typeof(RolCollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[PersistenceMode(PersistenceMode.InnerProperty)]
public Roller Roller
{
get
{
if (roller == null)
{
roller = new Roller();
} return roller;
}
}

Inaccessible due to its protection level in windows forms

This is the first problem I have encountered. Truly, I don't know why this is. I read on it a bit and made most of what I saw important public (if not all). So I thought maybe someone here can explain this. Also, I am trying to make it where when someone types in the withdrawl text box and clicked on it, the aMtBox will show such amount. Is this workable? Or am I doing something very wrong here
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
BankAccount a = new BankAccount();
public Form1()
{
InitializeComponent();
decimal iBa = 300.00m;
this.aMtBox.Text = iBa.ToString();
}
public void withdrawl_Click(object sender, EventArgs e)
{
MessageBox.Show("The balace is... {0:c2}", a.balance.ToString());
}
public class BankAccount
{
decimal balance;
decimal iBa;
decimal num1;
public decimal Balance
{
get { return balance;}
}
public decimal IBa
{
get { return iBa;}
}
public decimal Num1
{
get { return num1;}
}
public BankAccount()
{
iBa = 300.00m;
num1 = 0.00m;
balance = iBa - num1;
}
}
}
}
change
a.balance.ToString()
to
a.Balance.ToString()
a.balance is inaccessible to outer class due to being private.

Categories

Resources