Cole Z.
Cole Z.

Reputation: 83

C# Math.Sqrt() not working

So I am still rather new to C# programming, so I'm sure I'm making a very simple mistake here. I am using visual studio to make a console application and in this application, I am trying to find the square root of a number. I have the .NET framework.
Here is the top of my program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Linear
{
    public static class Math
    {
        static void Main()
        {
          // program in here
        }
     }
}

In the program, I have a line that goes like this:

double distanceA = Math.Sqrt(totalA);

So when I build the program with VS, it tells me that 'Linear.Math' does not contain a definition for 'Sqrt'. Why does it say this? How can I give it a definition for 'Sqrt'?

Upvotes: 2

Views: 4869

Answers (1)

Cyral
Cyral

Reputation: 14153

Because you named your class Math, Visual Studio and the compiler do not know if you are referring to your own class (Linear.Math), or the .NET Math class (System.Math).

You can specify that you would like to use the .NET Math class by instead by fully qualifying the name.:

double distanceA = System.Math.Sqrt(totalA);

This specifies you would like to use System.Math. You can use this throughout the entire file by adding the following after your using directives:

using Math = System.Math;

This is called the using alias directive, which will tell the compiler that Math refers to System.Math.

Note that it's usually not advised to use conflicting names when creating your own classes.

Upvotes: 25

Related Questions