Static Class and
Methods
Static classes and class members are used to create data and functions
that can be accessed without creating an
instance of the class.
The main
features of a static class are:
·
They only contain static members.
·
They cannot be instantiated.
·
They are sealed.
·
They cannot contain Instance Constructors(Instance
constructors are used to create and initialize instances. The class constructor
is invoked when you create a new object)
·
Static classes are sealed and therefore cannot be inherited
Static Constructor:
A static constructor is used to initialize any static data, or to perform a particular action once only.
·
A static
constructor does not take access
modifiers or have parameters.
·
A static
constructor is called automatically to
initialize the class before the first instance is created or any static
members are referenced.
·
A static
constructor cannot be called directly.
·
The user has no control on when the static constructor is executed
in the program.
·
Static
constructors are also useful when creating wrapper classes for unmanaged code.
class CompanyInfo
{
public static string GetCompanyName() { return
"CompanyName"; }
public static string
GetCompanyAddress() { return "CompanyAddress"; }
}
namespace consoleTestApplication
{
class Program
{
static void Main(string[] args)
{
string
COMPANYADDRESS = CompanyInfo.GetCompanyAddress();
}
}
}
Explicit Interface
Two interfaces that contain a member with the same signatureClass that implements those interfaces should call those methods explicitly.
interface ICpmpany
{
void
Display();
}
interface IBranch
{
void
Display();
}
class DisplayName
: ICpmpany, IBranch
{
// Both
ISurface.Paint and IControl.Paint call this method.
void ICpmpany.Display()
{
System.Console.WriteLine("company");
}
void IBranch.Display()
{
System.Console.WriteLine("branch");
}
}
namespace consoleTestApplication
{
class Program
{
static void Main(string[] args)
{
DisplayName
obj = new DisplayName();
//obj.Display(); // compile error
ICpmpany
cmpobj = (ICpmpany)obj;
IBranch
brcobj = (IBranch)obj;
cmpobj.Display();
brcobj.Display();
System.Console.ReadLine();
}
}
}
good stuff but rare posting...make weekly activity or daily activity.....waiting for your artilce....k viswa from Hyderabad.
ReplyDelete