How to implement static class using console application?


In this article, class is accessed without creating its instance, such class is called as static class. Whenever required methods do not need to be attached to a specific instance of the class, static class can be used. I hope this article will be useful for all beginners of .Net

How to implement static class using console application?
Description - If static class is implemented then you can prevent unnecessory instantiation. You can declare extension methods in the type.
Steps -
1) Add console application and add one class file in it which will contain static class.
Add following code in class file MyClass.cs.


using System;
using System.Collections.Generic;
using System.Text;

namespace ImplementStatic
{
static class MyClass
{
public static int Subtract(int number1, int number2)
{
return (number1 – number2);
}
}
}


2) Add following code in Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ImplementStatic

{
class Program
{
static void Main(string[] args)
{
MyClass.Subtract (20,4);
}
}
}

Here instead of creating object, we could directly access method through "MyClass.Subtract".
Instead of creating unnecessory instances of class, you can specify it as static. Static class implementation is very easy to use and understand.


Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: