4

I have a static member:

namespace MyLibrary
{
    public static class MyClass
    {
        public static string MyMember;
    }
}

which I want to access like this:

using MyLibrary;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            MyMember = "Some value.";
        }
    }
}

How do make MyMember accessible (without MyClass.) to MyApp just by adding using MyLibrary?

kazinix
  • 28,987
  • 33
  • 107
  • 157

1 Answers1

6

C# doesn't allow you to create aliases of members, only of types. So the only way to do something like that in C# would be to create a new property which is accessible from that scope:

class Program
{
    static string MyMember 
    {
       get { return MyClass.MyMember; }
       set { MyClass.MyMember = value; }
    }

    static void Main(string[] args)
    {
        MyMember = "Some value.";
    }
}

It's not really an alias, but it accomplishes the syntax you're looking for.

Of course, if you're only accessing / modifying a member on MyClass, and not assigning to it, this can be simplified a bit:

class Program
{
    static List<string> MyList = MyClass.MyList;

    static void Main(string[] args)
    {
        MyList.Add("Some value.");
    }
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • +1 for a valid solution. The only problem with this approach is, I have to create member for each class just to access the static member. – kazinix Jul 18 '13 at 03:31
  • 1
    @dpp correct, which is why this is going to be a pain. It's probably better to just stick with the conventional `MyClass.MyMember = "Some value."` – p.s.w.g Jul 18 '13 at 03:32
  • @dpp Also, mutable static fields are not only really bad code smell, they can be concurrency nightmares. I'd recommend avoiding them wherever possible. – p.s.w.g Jul 18 '13 at 03:38
  • Can you provide an example why mutable static fields should be avoided? A link maybe. Thanks! – kazinix Jul 18 '13 at 03:41
  • Here's a question which discusses it: http://stackoverflow.com/questions/7346496/using-static-method-and-variables-good-vs-bad. More info [here](http://blogs.tedneward.com/2008/02/22/Static+Considered+Harmful.aspx) and [here](http://c2.com/cgi/wiki?GlobalVariablesAreBad) – p.s.w.g Jul 18 '13 at 03:46