C# Class Library

142 Views Asked by At

I want to develop a class library in C# whose methods I would call in a hierarchical way, like this:

using MyProduct.Common;

protected void Page_Load(object sender, EventArgs e)
{
    Utils myUtils = new Utils();

    int res = myUtils.Numbers.Add(1, 2);
    string text = myUtils.Text.ToUpper("test"); //***
}

Is it possible to do, using Namespaces, classes, interfaces, whatever?

UPDATE: I have my library like this, but it doesn't work, as I can't "reference a type through an expression" (line with *** above)

namespace MyProduct.Common
{
    public class Utils
    {
        public static class Text
        {
            public static string ToUpper(string s)
            {
                return s.ToUpper();
            }
        }

    }
}

UPDATE 2: Ok, it seems I need to clarify... I have this MyProduct.Common.dll:

namespace MyProduct.Common
{
    public static class Utils
    {
        public static class Text
        {
            public static void ToUpper(string s)
            {
                return s.ToUpper();
            }
        }

        public static class Number
        {
            public static void Add(int a, int b)
            {
                return (a + b);
            }
        }
    }
}

and I have my project:

using MAD.Comum;
...
protected void Page_Load(object sender, EventArgs e)
{
   string x = Utils.Text.ToUpper("aa"); //this works
   string res = Utils.Number.Add(1, 2); //this works
}

and now 2 questions: - is it possible to separate classes Number and Text in 2 files? - is this a good design?

1

There are 1 best solutions below

6
On BEST ANSWER

Of course, you can do something like this:

namespace MyProduct.Common.Utils
{
    public static class Numbers
    {
        public static int Add(int n, int m)
        {
            return n + m;
        }
    }

    public static class Text
    {
        public static string ToUpper(string str)
        {
            return str.ToUpper();
        }
    }
}

And you use it like this:

MyProduct.Common.Utils.Numbers.Add(1, 2);

Hope this helps.

Cheers