motoDrizzt
motoDrizzt

Reputation: 1113

C# - adding data custom checks to the compiling process

Context: a simple base class which holds a name and a couple methods.

public abstract class BaseElement
{
    public string Name { get; set; }

    public abstract object GetDescription();

    public abstract void DoStuff();
}

A developer could subclass BaseElement, he will have to implement GetDescription() and DoStuff(), but can completely forget to assign a value to the Name property.

A simple solution would be to change the class this way:

public abstract class BaseElement
{
    public string Name { get; private set; }

    public abstract object GetDescription();

    public abstract void DoStuff();

    private BaseElement()
    {
    }

    public BaseElement(string name)
    {
            Name = name;
    }
}

So, this way when you subclass you are forced to assign a name. Still, you can always go as far as to use null or "".

Ok, then I can add a parameter check into the ctor and throw the relative exception, but...you'll discover the mistake only at run time, after you try to use the derived class.

So, the question: is it possible to add compilation-time rules to instruct the compiler to check for variables possible values, so that the problem is discovered at compile time and not at run time?

Upvotes: 0

Views: 43

Answers (1)

Sushil Mate
Sushil Mate

Reputation: 583

How about like this?

  public string Name
        {
            get { return _name; }
            private set
            {
                if (!string.IsNullOrWhiteSpace(value))
                    _name = value;
                else
                {
                    throw new Exception("Exception");
                }
            }
        }

Upvotes: 1

Related Questions