Reputation: 32936
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
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
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
Reputation: 51711
public Foo(Bar bar): base(bar == null ? "" : bar.name)
{...}
Upvotes: 1