Search code examples
c#exception

super statement in C#


I'm creating a class to manage exception in c#, and I'd like to create some constructor methods which recalls the superclass; this is the definition of my class:

class DataSourceNotFoundException: System.Exception 

but since in c# there is no super method what am I supposed to call to get the constructor methods of System.Exception?


Solution

  • You call a parent constructor using base before the body of the constructor:

    public class FooException : Exception
    {
        public FooException(string message) : base(message)
        {
        }
    }
    

    Obviously you don't have to just pass a parameter from your own constructor up as an argument to the base constructor:

    public class FooException : Exception
    {
        public FooException(int x) : base("Hello")
        {
            // Do something with x
        }
    }
    

    The equivalent to chain to a constructor in the current class is to use this instead of base.

    Note that constructor chaining works very slightly differently in C# compared with Java, with respect to when instance variable initializers are run. See my article on C# constructors for more details.