Loading, please wait...

A to Z Full Forms and Acronyms

10 Most Used Keywords In C#

Aug 16, 2018 CSharp, Programming , 4139 Views
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, so let’s see the list here:

  • 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 available all the classes, interfaces and abstract classes and their methods and properties 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:

using System.IO;   
using System.Text;  

 

To create an alias for a namespace or a type. This is called using alias directive. 

using MyProject = TruckingApp.Services;   

We can use the namespace alias as in the following:

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

using namespace1 = TruckingApp1.Services;   
using namespace2 = TruckingApp2.Services;   
using namespace3 = TruckingApp3.Services;   
  
namespace2.Truck newObj = new namespace2.Truck();   

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 defined in the table are 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.

 

Struct

Struct is an encapsulated entity. Struct doesn't uses complete oops concept but are used for user defined data type. All the member of the struct has 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 elements of other types.

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

Struct support 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.

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-user, 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.

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
{


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:

  1. 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:
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
    namespace ConsoleApplication13  
    {  
        abstract class mcn  
        {  
            public int add(int a, int b)  
            {  
                return (a + b);  
            }  
        }  
        class mcn1: mcn  
        {  
            public int mul(int a, int b)  
            {  
                return a * b;  
            }  
        }  
        class test  
        {  
            static void Main(string[] args)  
            {  
                mcn1 ob = new mcn1();  
                int result = ob.add(5, 10);  
                Console.WriteLine("the result is {0}", result);  
            }  
        }  
    }  
    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.
    
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
    namespace ConsoleApplication14  
    {  
        abstract class test1  
        {  
            public int add(int i, int j)  
            {  
                return i + j;  
            }  
            public abstract int mul(int i, int j);  
        }  
        class test2: test1  
        {  
            public override int mul(int i, int j)  
            {  
                return i * j;  
            }  
        }  
        class test3: test1  
        {  
            public override int mul(int i, int j)  
            {  
                return i - j;  
            }  
        }  
        class test4: test2  
        {  
            public override int mul(int i, int j)  
            {  
                return i + j;  
            }  
        }  
        class myclass  
        {  
            public static void main(string[] args)  
            {  
                test2 ob = new test4();  
                int a = ob.mul(2, 4);  
                test1 ob1 = new test2();  
                int b = ob1.mul(4, 2);  
                test1 ob2 = new test3();  
                int c = ob2.mul(4, 2);  
                Console.Write("{0},{1},{2}", a, b, c);  
                Console.ReadLine();  
            }  
        }  
    }  ​

     
     
    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.
  •  

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:
class Program  
{  
    class MyClass  
    {  
        public void MyMethod()  
        {}  
    }  
  
    static void Main(string[] args)  
    {  
        // Set a breakpoint here to see that mc = null.  
        // However, the compiler considers it "unassigned."  
        // and generates a compiler error if you try to  
        // use the variable.  
        MyClass mc;  
  
        // Now the variable can be used, but...  
        mc = null;  
  
        // ... a method call on a null object raises   
        // a run-time NullReferenceException.  
        // Uncomment the following line to see for yourself.  
        // mc.MyMethod();  
  
        // Now mc has a value.  
        mc = new MyClass();  
  
        // You can call its method.  
        mc.MyMethod();  
  
        // Set mc to null again. The object it referenced  
        // is no longer accessible and can now be garbage-collected.  
        mc = null;  
  
        // A null string is not the same as an empty string.  
        string s = null;  
        string t = String.Empty; // Logically the same as ""  
  
        // Equals applied to any null object returns false.  
        bool b = (t.Equals(s));  
        Console.WriteLine(b);  
  
        // Equality operator also returns false when one  
        // operand is null.  
        Console.WriteLine("Empty string {0} null string", s == t ? "equals" : "does not equal");  
  
        // Returns true.  
        Console.WriteLine("null == null is {0}", null == null);  
  
  
        // A value type cannot be null  
        // int i = null; // Compiler error!  
  
        // Use a nullable value type instead:  
        int ? i = null;  
  
        // Keep the console window open in debug mode.  
        System.Console.WriteLine("Press any key to exit.");  
        System.Console.ReadKey();  
  
    }  
}  

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 you with a simple practical demonstration.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace this_example  
{  
    class Program  
    {  
        public class Demo  
        {  
            int age;  
            string name;  
  
            public Demo(int age, string name)  
            {  
                age = age;  
                name = name;  
            }  
  
            public void Show()  
            {  
                Console.WriteLine("Your age is :" + age.ToString());  
                Console.WriteLine("Your name is : " + name);  
            }  
        }  
  
        static void Main(string[] args)  
        {  
            int _age;  
            string _name;  
  
            Console.WriteLine("Enter your age : ");  
            _age = Int32.Parse(Console.ReadLine());  
  
            Console.WriteLine("Enter your name : ");  
            _name = Console.ReadLine();  
  
            Demo obj = new Demo(_age, _name);  
  
            obj.Show();  
            Console.ReadLine();  
        }  
    }  
}  

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:

try  
{  
    int n = 5, m = 0;  
  
    if (m > 0)  
    {  
        int c = n / 5;  
    }  
    else  
    {  
        thorw new DivideByZeroException("Invalid Division");  
    }  
}  
Catch(DivideByZeroException ex)  
{  
    MessageBox.WriteLine("Invalid Dividion Found");  
}  

Finally

As per MSDN by using a finally block, you can clean up any resource that are 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-finallystatement, 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.

public class ThrowTestA  
{  
    static void Main()  
        {  
            int i = 123;  
            string s = "Some string";  
            object obj = s;  
  
            try  
            {  
                // Invalid conversion; obj contains a string, not a numeric type.  
                i = (int) obj;  
  
                // The following statement is not run.  
                Console.WriteLine("WriteLine at the end of the try block.");  
            }  
            finally  
            {  
                // To run the program in Visual Studio, type CTRL+F5. Then   
                // click Cancel in the error dialog.  
                Console.WriteLine("\nExecution of the finally block after an unhandled\n" +  
                    "error depends on how the exception unwind operation is triggered.");  
                Console.WriteLine("i = {0}", i);  
            }  
        }  
        // Output:  
        // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.  
        //  
        // Execution of the finally block after an unhandled  
        // error depends on how the exception unwind operation is triggered.  
        // i = 123  
}  

For details follow the link:

A to Z Full Forms and Acronyms