tags:

views:

145

answers:

3

If I have a class with two constructors like so

class Foo
{
    pubic 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?

A: 
public Foo(Bar bar): base(bar == null ? "" : bar.name)
{...}
Binary Worrier
+1  A: 

You can use a static method to do this.

class Foo
{
    pubic 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;
    } 
}
Marc Gravell
+1  A: 
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

Andreas Niedermair
This method seems fine, but I chose the static version as the answer for one simple reason, readability. Especially as I need to access 4 properties of the bar class which would make the constructor very unreadable
Sam Holder
:) that's ok ... i would rather tend to the ctor in the bar class which handles bar-objects ... have a nice day!
Andreas Niedermair