Pasindu Samaranayake
Pasindu Samaranayake

Reputation: 103

"Cannot implicitly covert type float? to float"

I'm trying to subtract 2 variables(float xdiff = x1 - x2;) of float format however I'm getting the error "Cannot implicitly covert type float? to float". Values d,c,s,m,radius,x1,y1,x2,y2 are obtained from windows forms input.

Code is as follows;

    public Nullable<float> d = null;

    public Nullable<float> c = null;

    public Nullable<float> s = null;

    public Nullable<float> m = null;

    public Nullable<float> radius = null;

    public Nullable<float> x1 = null;

    public Nullable<float> y1 = null;

    public Nullable<float> x2 = null;

    public Nullable<float> y2 = null;



private void Run_Click(object sender, EventArgs e)
        {
            d = float.Parse(this.downwind.Text);
            c = float.Parse(this.crosswind.Text);
            s = float.Parse(this.maxcross.Text);
            m = float.Parse(this.offset.Text);
            radius = float.Parse(this.rad.Text);
            x1 = float.Parse(this.x1coord.Text);
            y1 = float.Parse(this.y1coord.Text);
            x2 = float.Parse(this.x2coord.Text);
            y2 = float.Parse(this.y2coord.Text);

            float xdiff = x1 - x2;


        }

Upvotes: 1

Views: 86

Answers (2)

MKR
MKR

Reputation: 20095

If x1 and x2 are expected to be of type float? then result of operation x1 - x2 can be null (if ether value is null). Hence, the result is expected to be stored in float?. Nullable value types

You should use

float? xdiff = x1 - x2;

Or best could be:

var xdiff = x1 - x2;  //Using var will automatically decide type of result 

Upvotes: 1

Prateek Shrivastava
Prateek Shrivastava

Reputation: 1937

Assuming you take care of all NULL Scenarios, below should solve it.

float xdiff = (x1 - x2).Value;

Upvotes: 1

Related Questions