How to overload a constructor and also call the base class constructor in C #

0

I'm creating an error in C # that should extend the class Exception , but should also add an extra property, like this:

public class CampoVazioErro: Exception
{
    public string campo { get; }

        public CampoVazioErro(object c)
        {
            campo = c;
        }
        public CampoVazioErro(object c, string m) : base(m)
        {
        }
        public CampoVazioErro(object c, string m, Exception i) : base(m, i)
        {
        }
}

Can I call the base class constructor Exception and also call the simplest constructor in my class CampoVazioErro(object c) ? To my understanding there must be some way to do this but I'm not finding it on the internet.

  

Note: I know that to call another constructor within the same class I just have to pass this() in front of another constructor (eg CampoVazioErro(object c, string m): this(c) but I have no idea how to call this and also the constructor of my superclass.

A little help please?

    
asked by anonymous 03.04.2018 / 15:14

1 answer

1

Exception classes should always end with the word Exception . You should inherit from ApplicationException and not% with%. In fact the latter should be overlooked by developers in general. And even for this I consider the third signature an error.

Generally speaking, you should not use Exception as nothing. This is practically a legacy of language.

These constructors have no direct relationship with the base constructors. Just warning if you think you have it, the signatures are not different.

using System;

public class Program {
    public static void Main() {
        try {
            throw new CampoVazioException<int>(1);
        } catch (CampoVazioException<int>) {
            Console.WriteLine("deu erro");
        }
    }
}

public class CampoVazioException<T>: ApplicationException {
    public T Objeto { get; }

    public CampoVazioException(T objeto) : this(objeto, "") {}
    public CampoVazioException(T objeto, string mensagem) : base(mensagem) {
        Objeto = objeto;
    }
}
    
03.04.2018 / 15:30