Sam Holder
Sam Holder

Reputation: 32936

Can you check for null when a constructor call another constructor using the object given to the first constructor?

If I have a class with two constructors as follows:

class Foo
{
    public Foo(string name)
    {...}

    public Foo(Bar bar): base(bar.name)
    {...}
}

is there some way that I can check if bar is null before I get a null reference exception?

Upvotes: 4

Views: 1033

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1063013

You can use a static method to do this:

class Foo
{
    public Foo(string name) {
        ...
    }

    public Foo(Bar bar): base(GetName(bar)) {
        ...
    }

    static string GetName(Bar bar) {
        if(bar == null) {
            // or whatever you want ...
            throw new ArgumentNullException("bar");
        }
        return bar.Name;
    } 
}

Upvotes: 3

user57508
user57508

Reputation:

class Foo
{
    public Foo(Bar bar): base(bar == null ? default(string) : bar.name)
    {
        // ...
    }
}

alternatively let the bar-class handle with an object of the bar-class and throw an ArgumentNullException if you'd like

Upvotes: 2

Binary Worrier
Binary Worrier

Reputation: 51711

public Foo(Bar bar): base(bar == null ? "" : bar.name)
{...}

Upvotes: 1

Related Questions