Helpful Information
 
 
Category: .Net Development
C# Namespace Basic Questions

I just started C# programming recently and have a few questions about namespaces. How come the method "add" in class "Addition" has to be static to be accessible from Main(). (I got the examples from a book that doesn't explain this.) Here's the code:



namespace Math
{
class Addition
{
static public double add(params int[] numbers)
{
int total = 0;
for(int i=0; i<numbers.Length; i++)
{
total += numbers[i];
}
return total;
}
}
}


class MyMath
{
public static void Main()
{
double x = Math.Addition.add(1, 3, 5, 6);
System.Console.WriteLine(x);
}

}



Also, in the line "double x = Math.Addition.add(1, 3, 5, 6);" is this creating a new object? How come it doesn't use the keyword "new"? My next question is how do you create a new object from from a class in a namespace. For example, if I wanted to create an Addition object in the namespace using the keyword "new."

Any feedback is appreciated. Thanks!

In most classes you need to create an instance of the class before you can access the class's methods, properties and variables. The only time you don't have to do this is if you declare any of the above static, this means they will always exist and you will always be able to access them.


namespace Math
{
class Addition
{
public double lastTotal;

Addition()
{
lastTotal = 0.0;
}

public double add(params int[] numbers)
{
int total = 0;
for(int i=0; i<numbers.Length; i++)
{
total += numbers[i];
}
lastTotal = total;
return total;
}
}
}

The above class has a non-static variable (lastTotal) and method (add). This means that they are unique to each instance of the class, for example:


class MyMath
{
public static void Main()
{
Math.Addition Add1 = new Math.Addition();
Math.Addition Add2 = new Math.Addition();

Add1.add(1, 2);
Add2.add(1, 3);

System.Console.WriteLine(Add1.lastTotal); // prints 3
System.Console.WriteLine(Add2.lastTotal); // prints 4
}
}

As you can see Add1 and Add2 both have a unique value for lastTotal, if lastTotal was static they would both have printed 4 as the variable would exist once in memory, not twice. The above code also illustrates how you would access the method if it wasn't static and how to create an Addition object.

As for this:
double x = Math.Addition.add(1, 3, 5, 6);
You don't need the new key word because the add function is returning the object and thus is responsible for creating it. You also don't need the new key word period for primitive types (int, float, byte, char, etc.) For example here:
int total = 0;
You didn't need:
int total = new Int(0);

Hope that helps,
Nem

Ahh I see. That explains it. Thanks Nem!










privacy (GDPR)