C
C#2y ago
stigzler

What is this type of Overloading?

I'm converting from vb to c#. What's the correct term for the line public RelayCommand(Action<object> execute) : this(execute, null) in this overloading? It's very helpful:
public class RelayCommand : ICommand
{
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");

_execute = execute;
_canExecute = canExecute;
}

public RelayCommand(Action<object> execute) : this(execute, null)
{

}
}
public class RelayCommand : ICommand
{
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");

_execute = execute;
_canExecute = canExecute;
}

public RelayCommand(Action<object> execute) : this(execute, null)
{

}
}
10 Replies
Tvde1
Tvde12y ago
Constructor overload? Where one constructor calls the other
stigzler
stigzler2y ago
hey, thanks for the response. It was more the c# shortcut - i.e. putting the : this(execute,null) on the end, rather than typing RelayCommand(execute, null) in the method body. Having thought about it, maybe it doesn't have a name. I just need to find all these handy c# shortcuts. I thought it might have one as it's similar to the syntax for Inherits where you put a colon after the Class name e.g. : INotifyPropertyChanged
ero
ero2y ago
it's not a shortcut. it would be impossible to put that into the body
stigzler
stigzler2y ago
@Ero ? So replacing
public RelayCommand(Action<object> execute) : this(execute, null)
{

}
public RelayCommand(Action<object> execute) : this(execute, null)
{

}
with
public RelayCommand(Action<object> execute)
{
RelayCommand(execute, null);
}
public RelayCommand(Action<object> execute)
{
RelayCommand(execute, null);
}
wouldn't work?
Brady Kelly
Brady Kelly2y ago
Nope
stigzler
stigzler2y ago
Oh well - I know I'm fgoing to get a null reference exception if that's what you're meaning?
Brady Kelly
Brady Kelly2y ago
You just can't call a constructor from within a constructor, it can only be called with new and with the : this(<args>) notation
stigzler
stigzler2y ago
ah! Well that I would never have known! Thanks a bunch. What's the best reference for all these types of c# idiosyncrasies? That would have driven me potty if I'd have gotten stuck with that. Is there a site? I've done quite a bit of reading on the basics, but it's stuff like this that's going to catch me out
Brady Kelly
Brady Kelly2y ago
I don't know of a resource for all idiosyncracies but you can read up on constructor chaining in C#
stigzler
stigzler2y ago
Ha! and that answers the original question. "Constructor Chaining" Thanks again.