Home > OS >  Why can I assign doubles sometimes without value?
Why can I assign doubles sometimes without value?

Time:11-30

I wrote a small WF program which caculates some condensators and the ohmic law. I now want to tidy up a little bit. I ran across a issue where I use 2 doubles which both got assigned the value 0. I can remove the value from the voltage double. But not the current one. And I can't figure out why. Is there anything I am missing? Error Message is CS0165 Use of unassigned local variable 'current' and occurs in the line where the CalcResistance Method gets called

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Kondensator_Ohmsches_Gesetz_Calc
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {       
          
        }

        private void calcResistance_Click(object sender, EventArgs e)
        {
            double voltage;
            double current;
            bool ok = double.TryParse(textBox1.Text, out voltage) && double.TryParse(textBox2.Text, out current);
            if (ok)
            {
                textBox3.Text = Formulacollection.CalcResistance(voltage, current);
            }
            else
            {
                textBox3.Text = "Error Format not found";
            }
            textBox4.Text = Formulacollection.ConvertMicro(textBox3.Text);
            textBox5.Text = Formulacollection.ConvertMilli(textBox3.Text);
            textBox6.Text = Formulacollection.ConvertKilo(textBox3.Text);
            textBox7.Text = Formulacollection.ConvertMega(textBox3.Text);

        }
}

Formulacollection Class works like this:

using System;
using System.Collections.Generic;
using System.Text;
using static System.Math;
using System.Numerics;
using System.Globalization;

namespace Kondensator_Ohmsches_Gesetz_Calc
{
    public static class Formulacollection
    {
        public static string CalcResistance(double voltage, double current)
        {
            var resistance = voltage / current;

            return resistance.ToString();
        }
}

CodePudding user response:

The second part won't always be evaluated when you use the && operator. Try to use & instead of it, or set a default value to current when you declare it.

CodePudding user response:

Firstly CS0165 is the error occurs when using the uninitialized variable. But here the error occurs for the variable current which is initialized correctly. The brief about the error is here

So try the variable initialization globally in the class and then try to compile it.

Then there is a probability of the ok variable holding the value of two TryParse simultaneously, and also replace the && with &.

  • Related