Using Static statement in C# 6.0

Posted on Posted in .net, C#.net

In our previous article, we have discussed the new features introduced in C# 6.0. You can go through that here.

 

In this article, we will discuss on:

  • What is static statements in C#?
  • How to use Static statement in C# 6.0?

 

Static Keyword:

  1. Static is a keyword used with method and variables
  2. Static method can access only static fields.
  3. Static method cannot access non-static fields.
  4. Static method cannot be called using object of a class.
  5. Static method can be called using Class name.
  6. Static fields can be used using Class Name.

This is a great feature, that allows us to access static methods like they are globally available without specifying the class name.

Let’s look at an example to understand it better.

using System;
using System.Console;
public class Program
{
private static void Main()
{
WriteLine("New features in C# 6");
}
}

In the above example, you are no longer required to explicitly specify the type when calling the static WriteLine() method that belongs to System.Console class.

© 2015, www.techkatak.com. All rights reserved.

One thought on “Using Static statement in C# 6.0

  1. “static” is indeed quite useful. It is also frequently misused. It should be used only when needed, but I frequently see code that uses them like they’re the default way to design. Static can make code difficult to test if used liberally and nearly impossible to mock. It also, as you pointed out, makes code and data global to the application. Once a static is allocated, it is there until the application shuts down. I’ve seen plenty of usages of static dictionaries or lists that would have been better implemented as cache.

    Negative side-effects of static code includes, and might not be limited to, reduction of encapsulation, increase in coupling, elimination of over-riding (for static members). If not carefully used, it can completely obliterate inheritance. Unless the static is an extension method construct, statics cannot be accessed via interfaces.

    Essentially, static members are, in my opinion, inherently anti-object-oriented. If you understand how and when to use them, static members and classes are quite valuable. If you don’t, you can make your job, and that of your successors, very difficult.

Comments are closed.