Showing posts with label C# using alias static methods qualifier. Show all posts
Showing posts with label C# using alias static methods qualifier. Show all posts

16 July 2008

Using Static Alias

C# developers will be familiar with this syntax:

this.DoSomething();

whereby DoSomething() is some other method and qualifying it with the
this keyword is good practice. But how about static methods? You'll have to qualify it with the class name:

MyClass.DoSomeStaticThing();

I've never felt right qualifying static methods and properties within the class itself (it is of course required when calling from outside the class) and it gets a bit silly for really long class names, eg:

ServiceModelConfigurationSectionGroupCollection.DoSomeStaticThing();

That might be the worst case scenario class name, but when it is used more than once, the code starts looking littered:

MyVeryLongClassName.TryEnterReadLock(MyVeryLongClassName.Timeout, MyVeryLongClassName.IsReadOperation);

One option is to not qualify at all:

DoSomeStaticThing();

but this just doesn't promote good code clarity, especially when there are numerous static methods and/or properties that seem to float around with no qualifiers at all.

What I've started doing is using an alias called "This" which is just a shortcut to my class:

namespace MyNamespace{
using This = MyNamespace.MyVeryLongClassName;
public class MyVeryLongClassName{ ...

Now I can succinctly qualify static methods and properties:

This.DoSomeStaticThing();


There is an analogous distinction (albeit subtle) between
this (instance) and This (static) which is consistent with .NET naming conventions between class types (Pascal case) and instances (Camel case).