Question is how to prevent classes from getting instantiated
and getting derived from.
- Have a class with private constructor
- Make sure that the class is marked as sealed.
- Even though we do both the class can still have instance members as a part of it, which can be used as a type to declare a variable of sealed class type, which would be useless of course.
So in C# 2.0 the concept of static class was introduced, to
prevent a class from getting instantiated one can just mark the class as
static, some of the restrictions for the static classes are listed below:
You cannot have a instance property or method in a static
class. The code mentioned below may not compile:
public static class MobileDevice
//This should be static too
The correct version of the class will be :
public static class MobileDevice
public static class MobileDevice
{
//This should be static too
int broadcastBand;
int broadcastBand;
//This should be static too
[DllImport("user32.dll")]
extern int DeviceIOControl(string guid);
public static int BroadCastBand
{
get
{
return broadcastBand;
}
}
public static int DeviceID
{
get
{
return DeviceIOControl("49ECA277-65F7-446b-9206-4C09580DDD88");
}
}
}
The correct version of the class will be :
public static class MobileDevice
{
static int broadcastBand;
[DllImport("user32.dll")]
static extern int DeviceIOControl(string guid);
public static int BroadCastBand
{
get
{
return broadcastBand;
}
}
public static int DeviceID
{
get
{
return DeviceIOControl("49ECA277-65F7-446b-9206-4C09580DDD88");
}
}
}
If we try to use the
class by considering a static class as a type then compiler would complain: 'Cannot
declare a variable of static type'
class Program
class Program
{
static void Main(string[] args)
{
MobileDevice buart = null; //'Cannot declare a variable
of static type
Console.WriteLine(MobileDevice.DeviceID); //works
}
}
Also static class cannot
be marked as Sealed or Abstract.
No comments:
Post a Comment