I have some background in the python initializer (essentially Python object constructor syntax), and the syntax to instantiate an object in Python is as follows:
class Account:
def __init__(self,name=None,address="Not Supplied",balance=0.0):
this.name = name
this.address=address
this.balance=balance
Why is it, in C#, I have to provide defaults in the body of the constructor method, when in python I can declare them as optional, and default values are passed in (see the __init__
's signature):
public class Account
{
private string name;
private string address;
private decimal balance;
public Account (string inName, string inAddress, decimal inBalance)
{
name = inName;
address = inAddress;
balance = inBalance;
}
public Account (string inName, string inAddress)
{
name = inName;
address = inAddress;
balance = 0;
}
public Account (string inName)
{
name = inName;
address = "Not Supplied";
balance = 0;
}
}
Why can't I do the following in C#?
public class Account
{
private string name;
private string address;
private decimal balance;
public Account (string inName, string inAddress="not supplied", decimal inBalance=0;)
{
name = inName;
address = inAddress;
balance = inBalance;
}
Is it possible to have constructor syntax in C# that is similar (if not an exact duplicate) to Python's initializer syntax?
This has been done using Named and Optional Arguments (C# Programming Guide)
Visual C# 2010 introduces named and optional arguments. Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list. Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.
The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.
Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used.