10 Most Used Keywords In C#

We have a lot of keywords in C#, but we’ll learn the 10 most used keywords in this article. Let's have a look at the list:
  • using
  • class
  • struct
  • enum
  • interface
  • abstract
  • null
  • this
  • throw
  • finally

Using


Generally, we use the using keyword to add namespaces in code-behind and class files. Then it makes all the classes, interfaces and abstract classes and their methods and properties available in the current page. Adding a namespace can be done in the following two ways,
 
A. To allow the normal use of types in a namespace:
  1. using System.IO;   
  2. using System.Text;   
To create an alias for a namespace or a type. This is called using alias directive.
  1. using MyProject = TruckingApp.Services;   
We can use the namespace alias as in the following:
  1. MyProject.Truck newObj = new MyProject.Truck();   
This one (option B) is very useful when the same class/abstract/interface is present in multiple namespaces.

Let's say the Truck class is present in TruckingApp1, TruckingApp2 and TruckingApp3. Then it is difficult to call the Truck class of namespace2.

Here the alias directive gives an elegant syntax to use the Truck class.

Code
  1. using namespace1 = TruckingApp1.Services;   
  2. using namespace2 = TruckingApp2.Services;   
  3. using namespace3 = TruckingApp3.Services;   
  4.   
  5. namespace2.Truck newObj = new namespace2.Truck();   
For more details about using keyword follow the link,

Class


Class is a keyword in C#.NET which is used to create a class. Classes are special kinds of templates from which you can create objects. Each object contains data and methods to manipulate and access that data. The class defines the data and the functionality that each object of that class can contain.

A class declaration consists of a class header and body. The class header includes attributes, modifiers, and the class keyword. The class body encapsulates the members of the class that are the data members and member functions. The syntax of a class declaration is as follows:

Attributes accessibility modifiers class identifier: baselist { body }

Attributes provide additional context to a class, like adjectives, for example, the Serializable attribute. Accessibility is the visibility of the class. The default accessibility of a class is internal. Private is the default accessibility of class members. The following table lists the accessibility keywords,
 
Keyword Description
public Public class is visible in the current and referencing assembly.
private Visible inside current class.
protected Visible inside current and derived class.
Internal Visible inside containing assembly.
Internal protected Visible inside containing assembly and descendent of the current class.
 
Modifiers refine the declaration of a class. The list of all modifiers are defined in the table as follows,
 
Modifier Description
sealed Class can't be inherited by a derived class.
static Class contains only static members.
unsafe The class that has some unsafe construct likes pointers.
Abstract The instance of the class is not created if the Class is abstract.
 
For more details follow the link,

Struct


Struct is an encapsulated entity. Struct doesn't uses complete oops concept but is used for user defined data type. All the members of the struct have to be initialized, as it is value type.

A struct is a simple user-defined type, a lightweight alternative to a class. A structure in C# is simply a composite data type consisting of a number of elements of other types.

Similar to classes, structures have behaviors and attributes. As a value type, structures directly contain their value so their object or instance is stored on the stack.

Struct supports access modifiers, constructors, indexers, methods, fields, nested types, operators, and properties.

How to define struct
  1. public struct Student  
  2. {  
  3.    int id;  
  4.    int zipcode;  
  5.    double salary;  
  6. }  
Some points about structs
  • Struct is used to improve the performance and clarity of code.
  • Struct uses fewer resources in memory than class.
  • When we have small and frequent use of some work use struct over classes.
  • Performance can suffer when using structures in situations where reference types are expected due to boxing and unboxing.
  • You should pass structs to method as ref parameters in order to avoid the performance loss associated with copying data.
  • Structs reside on the stack, so we should keep them small.
  • Structs can't be inherited and we can say they are sealed.
  • Structure implicitly inherits from System.ValueType.
  • The default constructor of a structure initializes each field to a default value. You cannot replace the default constructor of a structure.
  • You can't define destructor for struct.
  • Struct can be inherited from an interface.
For more details follow the link,

Enum


Enum is use to create enums in C#.NET. An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.

Enum type can be integer (float, int, byte, double etc.). But if you used beside int it has to be cast.

enum is used to create numeric constants in .NET framework. All member of enum are of enum type. There must be a numeric value for each enum type.

The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
  1. enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};  
Some points about enum,
  • enums are enumerated data type in C#.
  • enums are not for end-users, they are meant for developers.
  • enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same.
  • Enumerations (enums) make your code much more readable and understandable.
  • enum values are fixed AND  enum can be displayed as a string and processed as an integer.
  • The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and ulong.
  • Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums.
  • enums are value types and are created on the stack and not on the heap.
For more details follow the link:

Interface


Interface is used to create an interface in C#. An interface looks like a class that can have a set of properties, methods, events and indexers, but has no implementation. The interface does not have an implementation of properties, methods, events and indexers because they are inherited by classes and structs, which must provide an implementation for each interface member.

An interface can be used to hide implementation details of classes from each other and it allows various objects to interact easily. It provides a separation between interface and implementation.

An interface is not only a contractual obligation to implement certain methods, properties, events and indexes but also provides a very low coupling between two classes. Interfaces in C# are provided as a replacement of multiple inheritances of classes because C# does not support multiple inheritance of classes.

Interfaces and abstract classes have similar purposes. Generally, an interface should be used when the implementation of the members it defines is not fixed, or when it is known that a single class requires the contents of several interfaces. Where the functionality of some members is fixed and the limited multiple inheritance facility is not required, abstract classes may be more appropriate.

How to create an Interface

Syntax

Interface interface_name
{
}


For more details follow the link:

Abstract


Abstract keyword is used to create class or as a method in C#, so let’s see how to use abstract keyword for creating class and also for method,
 
abstract class
 
If a class is defined as abstract then we can't create an instance of that class. By the creation of the derived class object where an abstract class is inherited from, we can call the method of the abstract class.

Let's take an example: First of all, select a console application and use the following code,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace ConsoleApplication13  
  6. {  
  7.     abstract class mcn  
  8.     {  
  9.         public int add(int a, int b)  
  10.         {  
  11.             return (a + b);  
  12.         }  
  13.     }  
  14.     class mcn1: mcn  
  15.     {  
  16.         public int mul(int a, int b)  
  17.         {  
  18.             return a * b;  
  19.         }  
  20.     }  
  21.     class test  
  22.     {  
  23.         static void Main(string[] args)  
  24.         {  
  25.             mcn1 ob = new mcn1();  
  26.             int result = ob.add(5, 10);  
  27.             Console.WriteLine("the result is {0}", result);  
  28.         }  
  29.     }  
  30. }  
In the above program we can call the method of the abstract class mcn with the help of an object of the mcn1 class which inherits from the class mcn. When we run the above program the output is the addition of 5 & 10 (i.e. 15) which is shown as:

Output
 
The result is 15
 
Abstract method
 
An Abstract method is a method without a body. The implementation of an abstract method is done by a derived class. When the derived class inherits the abstract method from the abstract class, it must override the abstract method. This requirement is enforced at compile time and is also called dynamic polymorphism.

The syntax of using the abstract method is as follows,

<access-modifier>abstract<return-type>method name (parameter)

The abstract method is declared by adding the abstract modifier the method.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace ConsoleApplication14  
  6. {  
  7.     abstract class test1  
  8.     {  
  9.         public int add(int i, int j)  
  10.         {  
  11.             return i + j;  
  12.         }  
  13.         public abstract int mul(int i, int j);  
  14.     }  
  15.     class test2: test1  
  16.     {  
  17.         public override int mul(int i, int j)  
  18.         {  
  19.             return i * j;  
  20.         }  
  21.     }  
  22.     class test3: test1  
  23.     {  
  24.         public override int mul(int i, int j)  
  25.         {  
  26.             return i - j;  
  27.         }  
  28.     }  
  29.     class test4: test2  
  30.     {  
  31.         public override int mul(int i, int j)  
  32.         {  
  33.             return i + j;  
  34.         }  
  35.     }  
  36.     class myclass  
  37.     {  
  38.         public static void main(string[] args)  
  39.         {  
  40.             test2 ob = new test4();  
  41.             int a = ob.mul(2, 4);  
  42.             test1 ob1 = new test2();  
  43.             int b = ob1.mul(4, 2);  
  44.             test1 ob2 = new test3();  
  45.             int c = ob2.mul(4, 2);  
  46.             Console.Write("{0},{1},{2}", a, b, c);  
  47.             Console.ReadLine();  
  48.         }  
  49.     }  
  50. }  
In the above program, one method; i.e. mul, can perform various functions depending on the value passed as parameters by creating an object of various classes which inherit other classes. Hence we can achieve dynamic polymorphism with the help of an abstract method.
For more details follow the link:

Null


As per MSDN, "The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables. Ordinary value types cannot be null."

We can use null to assaying any ref value in c# like any string value or any class object, array or any type of object.

The following example demonstrates some behaviors of the null keyword,
  1. class Program  
  2. {  
  3.     class MyClass  
  4.     {  
  5.         public void MyMethod()  
  6.         {}  
  7.     }  
  8.   
  9.     static void Main(string[] args)  
  10.     {  
  11.         // Set a breakpoint here to see that mc = null.  
  12.         // However, the compiler considers it "unassigned."  
  13.         // and generates a compiler error if you try to  
  14.         // use the variable.  
  15.         MyClass mc;  
  16.   
  17.         // Now the variable can be used, but...  
  18.         mc = null;  
  19.   
  20.         // ... a method call on a null object raises   
  21.         // a run-time NullReferenceException.  
  22.         // Uncomment the following line to see for yourself.  
  23.         // mc.MyMethod();  
  24.   
  25.         // Now mc has a value.  
  26.         mc = new MyClass();  
  27.   
  28.         // You can call its method.  
  29.         mc.MyMethod();  
  30.   
  31.         // Set mc to null again. The object it referenced  
  32.         // is no longer accessible and can now be garbage-collected.  
  33.         mc = null;  
  34.   
  35.         // A null string is not the same as an empty string.  
  36.         string s = null;  
  37.         string t = String.Empty; // Logically the same as ""  
  38.   
  39.         // Equals applied to any null object returns false.  
  40.         bool b = (t.Equals(s));  
  41.         Console.WriteLine(b);  
  42.   
  43.         // Equality operator also returns false when one  
  44.         // operand is null.  
  45.         Console.WriteLine("Empty string {0} null string", s == t ? "equals" : "does not equal");  
  46.   
  47.         // Returns true.  
  48.         Console.WriteLine("null == null is {0}"null == null);  
  49.   
  50.   
  51.         // A value type cannot be null  
  52.         // int i = null; // Compiler error!  
  53.   
  54.         // Use a nullable value type instead:  
  55.         int ? i = null;  
  56.   
  57.         // Keep the console window open in debug mode.  
  58.         System.Console.WriteLine("Press any key to exit.");  
  59.         System.Console.ReadKey();  
  60.   
  61.     }  
  62. }  
Follow the link for more details,

This


The this keyword refers to the current instance of the class. It can be used to access members within constructors, instance methods, and instance assessors.

Static constructors and member methods do not have a this pointer because they are not instantiated.

When you are writing code in method or property of a class, using "this" will allow you to make use of intelligence.

This keyword is used when you want to track the instance, which is invoked to perform some calculation or further processing relating to that instance.

Let me explain with a simple practical demonstration.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace this_example  
  7. {  
  8.     class Program  
  9.     {  
  10.         public class Demo  
  11.         {  
  12.             int age;  
  13.             string name;  
  14.   
  15.             public Demo(int age, string name)  
  16.             {  
  17.                 age = age;  
  18.                 name = name;  
  19.             }  
  20.   
  21.             public void Show()  
  22.             {  
  23.                 Console.WriteLine("Your age is :" + age.ToString());  
  24.                 Console.WriteLine("Your name is : " + name);  
  25.             }  
  26.         }  
  27.   
  28.         static void Main(string[] args)  
  29.         {  
  30.             int _age;  
  31.             string _name;  
  32.   
  33.             Console.WriteLine("Enter your age : ");  
  34.             _age = Int32.Parse(Console.ReadLine());  
  35.   
  36.             Console.WriteLine("Enter your name : ");  
  37.             _name = Console.ReadLine();  
  38.   
  39.             Demo obj = new Demo(_age, _name);  
  40.   
  41.             obj.Show();  
  42.             Console.ReadLine();  
  43.         }  
  44.     }  
  45. }  
For more details follow the link,

Throw


Throw keyword is used to used to throw an exception programmatically in C#.NET. The programmer can throw an exception to Catch block, for example, a condition is not met.

Example
  1. try  
  2. {  
  3.     int n = 5, m = 0;  
  4.   
  5.     if (m > 0)  
  6.     {  
  7.         int c = n / 5;  
  8.     }  
  9.     else  
  10.     {  
  11.         thorw new DivideByZeroException("Invalid Division");  
  12.     }  
  13. }  
  14. Catch(DivideByZeroException ex)  
  15. {  
  16.     MessageBox.WriteLine("Invalid Dividion Found");  
  17. }  
To know more about this follow the link,

Finally

 
As per MSDN by using a finally block, you can clean up any resource that is allocated in a try block, and run code even if an exception occurs in the try block. Typically, the statements of a finally block run when control leaves a try statement. The transfer of control can occur as a result of normal execution, execution of a break, continue, goto, or return statement, or propagation of an exception out of the try statement.

Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up. For more information,

Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important. However, if you have statements in a finally block that must be run even in that situation, one solution is to add a catch block to the try-finally statement. Alternatively, you can catch the exception that might be thrown in the try block of a try-finally statement higher up the call stack. That is, you can catch the exception in the method that calls the method that contains the try-finally statement, or in the method that calls that method, or in any method in the call stack. If the exception is not caught, execution of the finally block depends on whether the operating system chooses to trigger an exception unwind operation.

In the following example, an invalid conversion statement causes a System.InvalidCastException exception. The exception is unhandled.
  1. public class ThrowTestA  
  2. {  
  3.     static void Main()  
  4.         {  
  5.             int i = 123;  
  6.             string s = "Some string";  
  7.             object obj = s;  
  8.   
  9.             try  
  10.             {  
  11.                 // Invalid conversion; obj contains a string, not a numeric type.  
  12.                 i = (int) obj;  
  13.   
  14.                 // The following statement is not run.  
  15.                 Console.WriteLine("WriteLine at the end of the try block.");  
  16.             }  
  17.             finally  
  18.             {  
  19.                 // To run the program in Visual Studio, type CTRL+F5. Then   
  20.                 // click Cancel in the error dialog.  
  21.                 Console.WriteLine("\nExecution of the finally block after an unhandled\n" +  
  22.                     "error depends on how the exception unwind operation is triggered.");  
  23.                 Console.WriteLine("i = {0}", i);  
  24.             }  
  25.         }  
  26.         // Output:  
  27.         // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.  
  28.         //  
  29.         // Execution of the finally block after an unhandled  
  30.         // error depends on how the exception unwind operation is triggered.  
  31.         // i = 123  
  32. }  
For details follow the link,


Similar Articles