Wednesday, September 17, 2014

Static and Abstract keywords in C#

Access modifiers:

public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private
The type or member can only be accessed by code in the same class or struct.

protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

Static

The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created. A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.
Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.



class SomeClass 
    {
    public int InstanceMethod() { return 1; }
    public static int StaticMethod() { return 2; }
    }

In order to call InstanceMethod, you need an instance of the class:

SomeClass instance = new SomeClass();
instance.InstanceMethod();   //Fine
instance.StaticMethod();     //Won't compile

SomeClass.InstanceMethod();  //Won't compile
SomeClass.StaticMethod();    //Fine



Abstract class

Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy. What's special about them, is that you can't create an instance of them - if you try, you will get a compile error. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.  

Let's see how it works



Since all the members in the class Bob(name, alias, age) are declared public, it can be accessed outside the class Bob.



Here only alias is declared public, both age and name are declared private. Hence we can access only alias outside the class Bob. 


No comments:

Post a Comment