Static Classes and Members

A static class is a class which has only one instance. A static variable is a variable that exist per class where as normal or non-static member variables are per instance. Finally, a static method is method that can be called via class name, without creating the object of the class. Too much static things in one paragraph? Let us explain all of these concepts with the help of the following example.

using System;
namespace CSharpTutorials {

    public static class StClass {
        public static int age = 10;
        public static void incrementAge() {
            age++;
        }

        public static int returnAge() {
            return age;
        }
    }

    public class NStClass {
        public void incrementStaticAge() {
            StClass.age++;
        }
    }

    class Tutorial {
        static void Main(string[] args)  {
            NStClass nstclass = new NStClass();
            Console.WriteLine(StClass.returnAge()); // age at the beginning
            nstclass.incrementStaticAge(); // Age will become 11
            Console.WriteLine(StClass.returnAge());
            StClass.incrementAge();// Age will become 12
            Console.WriteLine(StClass.returnAge());
            Console.WriteLine();

            Console.ReadKey();
        }
    }
}

Download the code

In the above code, a static class named StClass has been defined,inside this class a static integer type variale named age has been declared. Next a method incrementAge has been defined which is also of static type. This method increments the static age variable by one. Another static static method named returnAge has been declared which returns the current value of age.

A non static class named NStClass has also been created in the code which contains a method incrementStaticAge(). This method also increment the age variable of the StClass.

There are some general rules regarding static classes, member variables and methods. A class is defined as static after adding a static keyword after the access modifier. A static class can only contain static methods and variables since non-static methods and variables are accessed via object of the class and static class cannot be instantiated. A static method can only access static members of the class as is the case with the incrementAge and returnAge methods of the StClass which could only access static age variable. Finally a static variable has only one instance, which means that if that variable is incremented by multiple functions, its value will keep on increasing.

Namespaces in C#

Namespaces in C# are used to package different classes with similar functionality. For instance, parent and child classes can be stored in the same namespace. If you look at the top of your code you see a statement using System; Here system is a namespace that contains different classes that contains system specific functionalities. For instance the Console class is a class within System namespace and it is used to display data on the console window.

You can create your own namespace using keyword namespace. Also, you can package as many classes within a namespace as you want. Have a look at the following example to see how namespaces are defined in C#.

using System;
namespace Namespace1 {
    public class Class1 {
        public void DisplayMessage() {
            Console.WriteLine("This method belongs to Class1 in Namespace1");
        }
    }
}

namespace Namespace2 {
    public class Class2 {
        public void DisplayMessage() {
            Console.WriteLine("This method belongs to Class2 in Namespace2");
        }
    }
}

namespace CSharpTutorials {
    class Tutorial {
        static void Main(string[] args) {

            Namespace1.Class1 c1obj = new Namespace1.Class1();
            Namespace2.Class2 c2obj = new Namespace2.Class2();

            c1obj.DisplayMessage();
            c2obj.DisplayMessage();

            Console.ReadKey();
        }
    }
}

Download the code

In the above code two namespaces Namespac1 and Namespace2 have been declared. The first namespace contains a class named Class1 while the second namespace contains Class2. To access a class within a namespace you need to write the name of the namespace followed by a dot operator and the class name. However, if you add namespace at the top via using keyword you do not need to write fully qualified class name. Have a look at this example.

using System;
using Namespace1;
using Namespace2;

namespace Namespace1 {
    public class Class1 {
        public void DisplayMessage() {
            Console.WriteLine("This method belongs to Class1 in Namespace1");
        }
    }
}

namespace Namespace2 {
    public class Class2  {
        public void DisplayMessage() {
            Console.WriteLine("This method belongs to Class2 in Namespace2");
        }
    }
}

namespace CSharpTutorials {
    class Tutorial  {
        static void Main(string[] args) {

            Class1 c1obj = new Class1();
            Class2 c2obj = new Class2();

            c1obj.DisplayMessage();
            c2obj.DisplayMessage();

            Console.ReadKey();
        }
    }
}

Download the code

In the above code Class1 and Class2 classes are being used without namespace names. This is because their namespaces have been added at the top via using keyword.

Extension Methods in C#

Extension methods are used to add additional functionality to the class by adding more methods to it, without changing the original definition of the class. Extension methods are always static methods and belong to a static class. The first parameter of an extension method is the class which is being extended and this modifier is used with the parameter name. Have a look at the following example to understand this concept.

using System;

namespace CSharpTutorials {
    public static class IntModifier {
        public static int Power(this int i, int j) {
            int result = i;
            for (int k = 1; k <= j; k++) result = result * i;            
            return result;        
        }
    }
    class Tutorial {
        static void Main (string[] args) {
            Console.WriteLine(10.Power(3));
            Console.ReadKey();
        }
    }
}

Download the code

In the above code a static class named IntModifier has been declared which contains a static method called TakeRoot. This static method has “this” prefixed with the first parameter which is of integer type. This means that this extension method shall extend the integer class. The next parameter is also an integer which denotes the power to which we want to raise our integer variable.

Inside the Main method TakeRoot method is being called on integer value of 10 and the power to which we take exponent of 10 is passed inside the parameter i.e. 3. The output of this method will be 1000 which shall be displayed on the screen.

Note, in the above example we did not change the actual implementation of the integer class, but we added an additional method which can help us easily take the power of integer variable to any desired number.

Exception Handling in C#

In simplest of the words, exception is basically an error in the program which either hampers the compilation of the code or crashes the code at runtime.

There are two types of exceptions in C#: Compile time errors and Run time exceptions.

Compile Time Errors

Compile time errors are those exceptions that do not let the code to compile. A typical example of a compile time exception is missing a semi-colon at the end of the line, missing a bracket and other similar syntax errors. Compile time errors are not dangerous as they are caught before actual execution of the program and can be corrected ahead of the execution.

Runtime Exceptions

Runtime exceptions are not caught at compile time. A program can be compiled even it has runtime errors. A typical example of a runtime exception is accessing array index which is out of bound or dividing a number by zero. Runtime exceptions are dangerous as they do not always occur and are never caught at runtime. Therefore, some special mechanism is required that can be used to handle these runtime exceptions.

In C#, try and catch statements are used to handle runtime exceptions. The code block which is vulnerable to runtime exceptions is enclosed inside the try block and the code that is to be executed if an exception occurs is enclosed in the catch block. Consider following example to see try and catch in action.

using System;
namespace CSharpTutorials {

    class Tutorial {
        static void Main(string[] args) {

            int numerator = 10;
            int denom = 0;
            int result;

            try {
                result = numerator / denom;
            }
            catch {
                Console.WriteLine("Division by zero not possible.");
            }
            Console.ReadKey();
        }
    }
}

Download the code

In the above code the denominator is zero, so when the program executes a runtime exception will occur. Since this code is within try block, the control will shift to catch block and the statements inside the catch block shall execute and program will not crash as is the case with un-handled exceptions.

C# Abstract class and abstract method

The C# abstract class is a class which cannot be instantiated. You can’t create object of an abstract class by simply using new keyword. Abstract class only serves as a base class for its child classes. An abstract is used to express a design concept or an abstract idea. A typical example of an abstract class is a shape or a vehicle. A vehicle is an abstract idea, but a car, jeep or a truck is a concrete form of a vehicle. Consider following example to see how an abstract class can be created in C#.
CSHarp abstract Class, methods

Abstract Class

using System;
namespace CSharpTutorials {

    public abstract class Vehicle {
        public string name;
        public int price;
        public int model;
        public Vehicle(string vname, int vprice, int vmodel) {
            name = vname;
            price = vprice;
            model = vmodel;
        }
    }

    public class Car : Vehicle {
        public int seating_capacity;
        // creating constructor and calling base class constructor as well
        public Car(string vname, int vprice, int vmodel, int capacity) : base(vname, vprice, vmodel) {
            seating_capacity = capacity;
        }
        public void DisplayInfo() {
            Console.WriteLine("\nThe name of the car is:" + name);
            Console.WriteLine("The price of the car is:" + price);
            Console.WriteLine("The model of the car is:" + model);
            Console.WriteLine("The seating capacity of car is:" + seating_capacity);
        }
    }

    public class Truck : Vehicle {
        public int load_capacity;
        public Truck(string vname, int vprice, int vmodel, int load) : base(vname, vprice, vmodel) {
            this.load_capacity = load;
        }
        public void DisplayInfo() {
            Console.WriteLine("\nThe name of the Truck is:" + name);
            Console.WriteLine("The price of the Truck is:" + price);
            Console.WriteLine("The model of the Truck is:" + model);
            Console.WriteLine("The load capacity of Truck is:" + load_capacity + " tons.");
        }
    }
    class Tutorial {
        static void Main(string[] args)  {
            // Creating objects of car and truck class
            Car car = new Car("Toyota", 750000, 2010, 5);
            Truck Truck = new Truck("HINO", 4200000, 2005, 300);
            car.DisplayInfo();
            Truck.DisplayInfo();
            Console.ReadKey();
        }
    }
}

Download the code

The above code is similar to the one in the article on classes and objects. However, in this case, the vehicle class is declared abstract. To mark a class abstract, the keyword abstract is appended before the name of the class. Now, if you want to create object of Vehicle class in the Main method, you will see that you wont be able to do that since Vehicle class is abstract.

Abstract methods or abstract functions

Like abstract classes, abstract methods have no concrete implementation. The Abstract method is declared via abstract keyword. Abstract method do not have a body since the body is implemented by the classes that derive the method. Derived class must provide definition for all the abstract methods of the class which they are inheriting. This is done via override keyword. Consider following example.

using System;
namespace CSharpTutorials {
    public abstract class Vehicle {

        public string name;
        public int price;
        public int model;

        public  Vehicle(string vname, int vprice, int vmodel) {
            name = vname;
            price = vprice;
            model = vmodel;
        }
        public abstract void DisplayInfo();
    }

    public class Car : Vehicle {
        public int seating_capacity;
        // creating constructor and calling base class constructor as well
        public Car(string vname, int vprice, int vmodel, int capacity) : base(vname, vprice, vmodel) {
            seating_capacity = capacity;
        }
        public override void DisplayInfo() {
            Console.WriteLine("\nThe name of the car is:" + name);
            Console.WriteLine("The price of the car is:" + price);
            Console.WriteLine("The model of the car is:" + model);
            Console.WriteLine("The seating capacity of car is:" + seating_capacity);
        }
    }

    public class Truck : Vehicle {

        public int load_capacity;
        public Truck(string vname, int vprice, int vmodel, int load) : base(vname, vprice, vmodel) {
            this.load_capacity = load;
        }
        public override void DisplayInfo() {
            Console.WriteLine("\nThe name of the Truck is:" + name);
            Console.WriteLine("The price of the Truck is:" + price);
            Console.WriteLine("The model of the Truck is:" + model);
            Console.WriteLine("The load capacity of Truck is:" + load_capacity + " tons.");
        }
    }

    class Tutorial{
        static void Main(string[] args) {
            // Creating objects of car and truck class
            Car car = new Car("Toyota", 750000, 2010, 5);
            Truck Truck = new Truck("HINO", 4200000, 2005, 300);

            car.DisplayInfo();
            Truck.DisplayInfo();
            Console.ReadKey();
        }
    }    
}

Download the code

In the above code, the DisplayInfo method has been declared as abstract in the Vehicle class. The child classes Car and Truck override this method and provide implementation for it.

Further reading:

What is the difference between abstract method and a virtual method?

An abstract function does not have any functionality. It’s just a signature. You’re saying, any child class MUST give their own version of this method, however it’s too general to even try to implement in the parent class. A virtual function, on the other hand is “here’s the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality”. Stack overflow has some good discussion about this topic.

Also in cases you may need to define an abstract C# class without any abstract methods in it. Here is a discussion why we need abstract classes that do not have any abstract methods.

Are abstract structures possible in C#?

Abstract structures are not possible in C# since:

  • Structs in C# are sealed and live on the stack as opposed to classes that live on the heap
  • C# does not let structs inheritance.

Can C# abstract class be derived from Interface?

Yes. C# abstract classes can implement interfaces. Here is an example.

 

 

 

Virtual Methods in C#

In simplest word, a virtual method in C# is a method that can have different implementation in parent and child classes. Virtual methods are used to achieve type base polymorphism where the usage of the function is different from its implementation.

Virtual methods are created via virtual keyword, while the child classes that implement their own implementation of the method override this virtual method via override keyword. Have a look at the following example to understand this concept.

using System;

namespace CSharpTutorials {

    public abstract class Vehicle {

        public virtual void VirtualMethod() {
            Console.WriteLine("This is a parent class method");
        }

    }

    public class Car : Vehicle {

        public override void VirtualMethod() {
            Console.WriteLine("This is an overriden child class method");
        }
    }

    public class Truck : Vehicle {
     
    }

    class Tutorial {
        static void Main(string[] args) {
            // Creating objects of car and truck class
            Car car = new Car();
            Truck truck = new Truck();

            car.VirtualMethod();
            truck.VirtualMethod();

            Console.ReadKey();
        }
    }
}

Download the code

In the above code, a virtual method named VirtualMethod has been define inside the parent Vehicle class. It displays a message which reads that this is the method in parent class. The Car and Truck class inherit this Vehicle class. Car class overrides the parent class virtual method and provides its own implementation while the Truck doesn’t override the VirtualMethod of the vehicle class.

Now, if VirtualMethod is called from the object of the Car class the run time will check if the Car class has an overriden version of the VirtualMethod method? If yes then call the VirtualMethod from the Car class. On the other hand if the VirtualMethod is called from the object of the Truck class the .net runtime will call the VirtualMethod method of the parent Vehicle class since Truck class doesn’t contain an overridden implementation of the method.

Polymorphism in C#

Polymorphism refers to the phenomena where you have a single interface that can perform multiple functionalities. In C#, polymorphism is of two types: Static Polymorphism and Dynamic Polymorphism. Both of these types have been explained below.

Static Polymorphism

Static Polymorphism can be achieved by creating method with the same name but different number or types of parameters. This is best explained with the help of following example.

using System;
namespace CSharpTutorials {

    public class Messages {

        public void DisplayType(int abc)  {
            Console.WriteLine("An int has been passed to this method");
        }

        public void DisplayType(string abc)  {

            Console.WriteLine("A string has been passed to this method");
        }

        public void DisplayType(char abc) {

            Console.WriteLine("A character has been passed to this method");
        }

        public void DisplayType(bool abc) {
            Console.WriteLine("A bool has been passed to this method");
        }
    }

    class Tutorial {
        static void Main(string[] args) {

            Messages msg = new Messages();
            msg.DisplayType(10);
            msg.DisplayType("hey");
            msg.DisplayType('c');
            msg.DisplayType(false);
            Console.ReadKey();
        }
    }
}

Download the code

In the above example, a class named Message has been defined. Inside this class four methods with the same name DisplayType have been declared. The only difference is the type of parameter that is passed to them. When these methods are called the method whose parameters match with those in the method call, will be executed. This is phenomena is known as method overloading and static overloading is achieved via this.

Dynamic Polymorphism

Dynamic Polymorphism is implemented via inheritance, abstract and virtual method. You can store object of the child class in the parent class variable and then if you call the method on that parent class object, it will call the child class method since it is storing reference of the object of the child class. This is explained in the following example.

using System;

namespace CSharpTutorials {

    public class Vehicle {
        public virtual void DisplayMessage() {
            Console.WriteLine("This is a parent class method");
        }
    }

    public class Car : Vehicle {
        public override void DisplayMessage() {
            Console.WriteLine("This is an overridden child class method in Car");
        }
    }

    public class Truck : Vehicle {
        public override void DisplayMessage()    {
            Console.WriteLine("This is an overridden child class method in Truck");
        }
    }

    class Tutorial {
        static void Main(string[] args) {
            // Creating objects of car and truck class
            Vehicle v = new Vehicle();
            Vehicle car = new Car();
            Vehicle truck = new Truck();
            v.DisplayMessage();
            car.DisplayMessage();
            truck.DisplayMessage();
            Console.ReadKey();
        }
    }
}

Download the code

In the Main method, three vehicle type variables v, car and truck have been declared which stores references of Vehicle, Car and Truck objects. When DisplayMessage method is called on each object the implementation of the method intrinsic to each class will be executed which means you have single interface but different functionalities i.e. polymorphism.

Interfaces in C#

Interfaces are basically a contract between the classes that implement the interface. Interfaces specify that a class must contain these members. However and interface do not provide implementation for its members. The class that implements the interface provides the definition for the interface members. In simple words, the “what” part of the contract is contained by the interface and the “how” part of the contract is implemented by the class.

using System;
namespace CSharpTutorials {

    public interface IMessageDisplay {
       void Message1();
        int add(int a, int b);
        void DisplayString(string s);
    }

    public class Messages: IMessageDisplay {
        public void Message1() {
            Console.WriteLine("Some random message.");
        }
        public int add(int n1, int n2) {
            return n1 + n2;
        }
        public void DisplayString(string a) {
            Console.WriteLine(a);
        }
    }

    class Tutorial {
        static void Main(string[] args) {
          
            Messages msg = new Messages();
            msg.DisplayString("this is a message");
            msg.Message1();
            Console.WriteLine(msg.add(150, 200));
            Console.ReadKey();
        }
    }
}

Download the code

In the above code, an interface IMessageDisplay has been defined. Interfaces are defined like classes, however for interfaces, the keyword interface is used. The IMessageDisplay interface declared in the above code has three methods Message1, Add and DisplayString. These methods do not contain any implementation. Next, a class Messages has been declared which implements this IMessageDisplay interface. The Messages class has to implement the Message1, Add and DisplayString methods and provide its implementation. A class implements message using a “:” which was the case with inheriting from other classes.

Inheritance in C#

In real world inheritance refers to the phenomena of adopting physical features, characteristics and wealth of parents. In C#, the concept is similar. A class can inherit properties of its parent class via inheritance. In C#, only single inheritance is possible which means that a class cannot inherit from multiple classes. However, multiple classes can inherit from one class. The class which is being inherited is called the parent or base class and the class which inherits the base class is called child or derived class.

Inheritance is handy where multiple classes have some as well as different characteristics. All the common characteristics are packaged into the parent class while the properties intrinsic to each individual class are encapsulated within that class. Consider example of a Car and Truck, both of them have some name, price and model. However truck can have a property called load capacity while car may have a property called seating capacity. In such cases the first three properties i.e name, price and model will be packaged into parent class Vehicle. The load capacity property will be encapsulated inside Truck class while seating capacity property will be enclosed inside a Car class. To inherit a class, the colon operator “:” is used followed by the name of the class to inherit. Have a look at the following example to understand the concept of inheritance in C#.

using System;

namespace CSharpTutorials {
    public class Vehicle {

        public string name;
        public int price;
        public int model;

        public Vehicle(string vname, int vprice, int vmodel)  {
            name = vname;
            price = vprice;
            model = vmodel;
        }
    }

    public class Car : Vehicle {
        public int seating_capacity;

        // creating constructor and calling base class constructor as well
        public Car(string vname, int vprice, int vmodel, int capacity) : base(vname, vprice, vmodel) {
            seating_capacity = capacity;
        }

        public void DisplayInfo() {
            Console.WriteLine("\nThe name of the car is:" + name);
            Console.WriteLine("The price of the car is:" + price);
            Console.WriteLine("The model of the car is:" + model);
            Console.WriteLine("The seating capacity of car is:" + seating_capacity);
        }
    }

    public class Truck : Vehicle  {

        public int load_capacity;
        public Truck(string vname, int vprice, int vmodel, int load) : base(vname, vprice, vmodel) {
            this.load_capacity = load;
        }

        public void DisplayInfo() {
            Console.WriteLine("\nThe name of the Truck is:" + name);
            Console.WriteLine("The price of the Truck is:" + price);
            Console.WriteLine("The model of the Truck is:" + model);
            Console.WriteLine("The load capacity of Truck is:" + load_capacity +" tons.");
        }
    }

    class Tutorial {
        static void Main(string[] args) {
            // Creating objects of car and truck class
            Car car = new Car("Toyota", 750000, 2010, 5);
            Truck Truck = new Truck("HINO", 4200000, 2005, 300);

            car.DisplayInfo();
            Truck.DisplayInfo();
            Console.ReadKey();
        }
    }    
}

Download the code

CSharp Class, Object

C# is an object oriented language which means that each and every functionality of a C# program is written inside some CSharp Class. The Main method which is the starting point of any C# program is also written inside some class. This article explains what classes and objects are.

CSHarp Class, Sub Class and Objects

CSharp Class

CSharp Class, like structures, let you define your own data type. A class has no physical existence in the memory of a computer. It only provides template for the data type. Class can be seen as a map which only provides a blueprint for the design of the house, it is not the actual house, yet it is prerequisite to building an appropriate house.Unlike structures, a class data type is a reference type. A class can hold member variables and functions.

CSharp Object

Strictly speaking, an object is anything that has some characteristics and can perform some functions. In C#, an object is physical representation of a class. An object implements all the characteristics of it class. Consider following example to understand how a class can be defined and its object can be created in C#.

using System;
namespace CSharpTutorials {

    public class Vehicle {
        public string name;
        public int price;
        public int model;
        public Vehicle(string vname, int vprice, int vmodel) {
            name = vname;
            price = vprice;
            model = vmodel;
        }
        public void DisplayInfo() {
            Console.WriteLine("\nThe name of the vehicle is:"+name);
            Console.WriteLine("The price of the vehicle is:" + price);
            Console.WriteLine("The model of the vehicle is:" + model);
        }
    }
    class Tutorial {
        static void Main(string[] args) {
            // Creating objects of Vehicle class
            Vehicle car1 = new Vehicle("Ford", 230000, 2000);
            Vehicle car2 = new Vehicle("BMW", 345000, 2005);

            car1.DisplayInfo();
            car2.DisplayInfo();
            Console.ReadKey();
        }
    }    
}

Download the code

In the above code a class named Vehicle has been declared which contains three member variables name,price and variable. It also contains a public method Vehicle which has no return type (not even void). This is the constructor. Whenever the object of a class is created this constructor method is called. You can also pass parameters to the constructor as has been done in the above code. This constructor initializes member variables of the Vehicle class. The class, also contains a member function called DisplayInfo which displays the values of the three member variables of the vehicle class.

Inside the Main function two objects of the Vehicle class have been created namely car1 and car2. Notice, these objects have been created via new keyword followed by the parameterized constructor of the vehicle class. Then using these objects, the DislayInfo method is called via dot operators.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .