Yvette Yvette - 3 months ago 8
C# Question

Are uninitialised attributes given default values as they are when using the default constructor?

If creating a serial port with the default constructor or parameterless constructor, the port is given default values. From the documentation:

// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();



This constructor uses default property values when none are specified. For example, the DataBits property defaults to 8, the Parity property defaults to the None enumeration value, the StopBits property defaults to 1, and a default port name of COM1.


There are several constructors

enter image description here

When using a constructor with parameters:

Are the attributes that are not within the parameters of the constructor of the serial port given the same default values when using a constructor with parameters and when using the default constructor?

The problem in this question, the interesting answers, comments and subsequent chat discussion let me to ask this.

Answer

You can take a look at its source code and see constructors and filed definitions.

You will see all important properties including PortName, BaudRate, DataBits, Parity and StopBits have default values which if they are not present in constructor arguments, the default value will be used for them. Also some other important properties like HandShake has default values as well, while they are not present in constructors.

public SerialPort(System.ComponentModel.IContainer container)
{
    container.Add(this);
}
public SerialPort()
{
}
// Non-design SerialPort constructors here chain, 
//using default values for members left unspecified by parameters
public SerialPort(string portName) 
    : this (portName, defaultBaudRate, defaultParity, defaultDataBits, defaultStopBits)
{
}
public SerialPort(string portName, int baudRate) 
    : this (portName, baudRate, defaultParity, defaultDataBits, defaultStopBits)
{
}
public SerialPort(string portName, int baudRate, Parity parity)
    : this (portName, baudRate, parity, defaultDataBits, defaultStopBits)
{
}
public SerialPort(string portName, int baudRate, Parity parity, int dataBits)
    : this (portName, baudRate, parity, dataBits, defaultStopBits)
{
}
public SerialPort(string portName, int baudRate, Parity parity, 
     int dataBits, StopBits stopBits)
{
    this.PortName = portName;
    this.BaudRate = baudRate;
    this.Parity = parity;
    this.DataBits = dataBits;
    this.StopBits = stopBits;
}

And here is those fields:

private int baudRate = defaultBaudRate;
private int dataBits = defaultDataBits;
private Parity parity = defaultParity;
private StopBits stopBits = defaultStopBits;
private string portName = defaultPortName;
Comments