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?
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?
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;
}
}
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