Understanding Different Class Member Modifiers in C# (C Sharp)

C# ensures data encapsulation by using modifiers. These modifiers can be classified into access modifiers (public, private, protected, internal), class member modifiers (const, event, override, extern, static, readonly, abstract, virtual) and other additional modifier called sealed.

This article will help you in understanding the purpose and usage of class member modifiers. The class member modifiers are used to modify the class member’s behavior. As mentioned above, C# supports eight different class member modifiers which are explained below:

Const: If you want to prevent a member variables value from getting altered, use const modifier. This modifier can be applied only on class variables and not on its methods. Here is an example:

public class testClass{
public const double constOmega = 0.5671;
public static void Main(){
//do mathematical computations with omega constant
}
}

Event: Notification of an event occurrence between classes is achieved using the event modifier. Event modifier is closely related with delegates. While coding, declare a delegate and define an event for that delegate. You can declare a delegate as follows:

public delegate void MyDelegate();
You can create an event as follows:
event MyDelegate MyEvent;
You can now fire and handle the event in later part of your code.

Override: When you want to extend and implement an abstract or virtual method, use override modifier. For example, car is an abstract class with engineConfiguration as its method. If any class inherits from car, it has to override engineConfiguration method.

abstract class car {
abstract public void engineConfiguration();
}
class indicaCar : car {
public override void engineConfiguration(){}
}
Ensure that you don’t override non-virtual or static methods. That will end up in error. Both properties and methods of a class can be applied with this modifier.

Extern: If you want to use a method or function that is implemented outside your c# code, then you can do it by using extern modifier. Here is an example:
public class MyClass {
[DllImport("testExtern.dll")]
public static extern testFunction( out string strOutput );

public void callExternFunction() {
string strVar;
testFunction( out strVar);
}
}

In this example you are accessing a method called testFunction whose implementation is available in testExtern.dll. Methods accessed using extern modifier is called as external methods. Ensure that you follow the guidelines given below while using extern modifier:

• External method should not include method body in your code
• Extern modifier should not be used with abstract Modifier
• External method should be declared static when accessed using DllImport
• Methods, properties and even constructor, destructor of your Class can include this modifier

Static: In normal scenarios, you will access class members using instance of the class. Each member will be initialized and maintained separately for each instance of the class. What if you want a member to be unique to the class and its value retained class level rather than object level? In that case you can use the modifier static. Assume that you want to know the number of instances created for a class, how will you achieve it?

public class testStatic{
public static int countInstances = 0;
public testStatic(){
countInstances++;
}
}
public class printCount{
public static void Main(){
testStatic object1 = new testStatic();
testStatic object2 = new testStatic();
System.Console.WriteLine(testStatic.countInstances);
}
}

Output will be 2. Also note that the static variable countInstances is called using the class name and not the object name.

Readonly: You might require a constant in your code which cannot be evaluated at compile time or it cannot be initialized during declaration itself. In those cases, you cannot use const modifier. However, you can use the class member modifier readonly. ReadOnly variables can be initialized once either during its declaration or in the class constructor and they cannot be altered further. Here is an example:
public class testReadOnly {
public static readonly int readOnlyVar;
static testReadOnly() {
readOnlyVar = 100;
}
public static void Main() {
System.Console.WriteLine(readOnlyVar);
}
}

The output will be 100. Similar to constants, you cannot change the value of a readonly variable. If you include the code “readOnlyVar = 500;” inside your Main() method, then the compilation error CS0198 stating “A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)” will be thrown. Remember that this modifier can be applied only on class member variables and not on its methods.

Abstract: Use abstract modifier on a property or method of a class if you want to implement the class only in the derived class and not in the parent class. Example given for the modifier override will cover usage of abstract modifier as well. Ensure that you follow the guidelines given below when you are using abstract modifier on a class member:

• You can declare a class member as abstract, only if the class is defined as abstract
• Abstract class member should not have any implementation
• Abstract class member has to be implemented by the class that derives from the abstract class
• The method implementation in the derived class should include the modifier override
• Do not use static or override or virtual keywords along with abstract modifier in a method

Virtual: Assume that there is a method which is implemented in base class and overridden in derived class. If you want to trigger the method by identifying the instance type at run time rather than at compile time, then you can use the Virtual modifier, which can be applied to both properties as well as methods of a class. Here’s an example:

class baseClass {
public virtual void testMethod() { Console.WriteLine("base class method is triggered"); }
}
class derClass: baseClass{
public override void testMethod() { Console.WriteLine("derived class method is triggered"); }
}
class TestVirtual {
static void Main() {
derClass derObj = new derClass();
baseClass baseObj= derObj;
baseObj.testMethod();
derObj.testMethod();
}
}

Both baseObj.testMethod() and derObj.testMethod() will call the overridden method, this is because baseObj is referring to derived class object. Ensure that virtual modifier should not be used along with abstract or static or override modifiers.

|How and Why to Use Trace Option for Debugging in ASP.NET Application | How to Display Tool Tip in Your ASP.NET Web Application | How to Use “const” Class Member Modifier in C# | How to Use HTML Help Viewer in Your ASP.NET Web Application | List of Preprocessor Directives Available in C# | More about #define, #undef and Conditional Compilation Directives in C# |Understanding Different Class Member Modifiers in C# | Understanding of Diagnostic Directives and #pragma, #line, #region, #endregion Directives in C# | Usage of Roles API to Perform Authorization in .NET| What are the Different Compiler Engineering Techniques|Writing Unsafe Code in C#|

 


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.