public bool IsNum(char ch)
		{
			if (((ch >= '0') && (ch <= '9'))|| (ch == '.'))
				return true;
			else
				return false;
		}

Why does this method work in a normal console app, but not in a class library that I am trying to write?

If I copy this code into my class library I get:

: "Expected class, delegate, enum, interface, or struct"


Simon

That builds just fine for me. Are you sure you put the method in the right place? like so:

public class Class1
{
 public bool IsNum(char ch)
        {
            if (((ch >= '0') && (ch <= '9')) || (ch == '.'))
                return true;
            else
                return false;
        }
}

remember methods need to be defined within a class.

Ya, I figured out a few moments later that it wasn't inside my class. However, what if I wanted a global function(method) that could be used by multiple classes? I ask this because I originally had about 4 classes built, and I wanted that IsNum() to work with each of them. I have since re written it so that there is only one class so it works out. But what if I had NEEDED mutiple classes that could each use a method like IsNumber()?

As long as all the classes are in the same project, add a static keyword to the method declaration and change the modifier to public:

public static bool IsNum

Now in your other classes, call it like

Class1.IsNum();

If they are NOT in the same project (or if you plan to recycle this method) what you could probably do, is make a class library (.dll) project and have a class within that library (let's call it MathMethods) that contains that method. You would then add the static keyword to the function declaration:

public static bool IsNum

Next, you would add the project that contains the MathMethods class, or its built dll as a reference to any project that contains a class you want to use IsNum in.

You would import the namespace you wrote the MathMethods class in (using directive).

Then in your code, call it as:

MathMethods.IsNum(chr);

I realise that solution isn't exactly ideal if it's just that one method you want to access anywhere, but it's the only way I know to get a method "global".

The static keyword is used so that the method executes independent of an instance of the class. Thus in writing static methods you must remember that you are not allowed to manipulate instance variables (variables that would only exist if an instance of the class is created).

Hope this helps

What?

Member Avatar for iamthwee

My comment was directed at simon. It looks like he is using elements of my snippet (see the link I posted) to write his infix to postfix calculator in c#. I was just making him aware that the code I had written is not bug free.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.