/// </returns>
public static unsafe proc_stats GetThreadInfo(int pid, int tid)
{
- proc_stats ret = new proc_stats();
+ proc_stats ret = default;
kinfo_proc* info = null;
int count;
throw new ArgumentOutOfRangeException(nameof(pid), SR.NegativePidNotSupported);
}
- rusage_info_v3 info = new rusage_info_v3();
+ rusage_info_v3 info = default;
// Get the PIDs rusage info
int result = proc_pid_rusage(pid, RUSAGE_INFO_V3, &info);
SafeBignumHandle qx_bn, qy_bn, d_bn;
IntPtr d_bn_not_owned;
int qx_cb, qy_cb, d_cb;
- ECParameters parameters = new ECParameters();
+ ECParameters parameters = default;
bool refAdded = false;
try
int cbSubgroupOrder = GetMax(order_cb, d_cb);
// Copy values to ECParameters
- ECParameters parameters = new ECParameters();
+ ECParameters parameters = default;
parameters.Q = new ECPoint
{
X = Crypto.ExtractBignum(qx_bn, cbFieldLength),
int AccessMask,
out SafeLsaPolicyHandle PolicyHandle)
{
- var systemNameUnicode = new UNICODE_STRING();
+ UNICODE_STRING systemNameUnicode = default;
if (SystemName != null)
{
fixed (char* c = SystemName)
public static BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO Create()
{
- BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO ret = new BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO();
+ BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO ret = default;
ret.cbSize = sizeof(BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO);
Span<NCryptBuffer> parameters = stackalloc NCryptBuffer[4];
int parameterCount = 0;
// We always need to marshal the hashing function
- NCryptBuffer hashAlgorithmBuffer = new NCryptBuffer();
+ NCryptBuffer hashAlgorithmBuffer = default;
hashAlgorithmBuffer.cbBuffer = (hashAlgorithm.Length + 1) * sizeof(char);
hashAlgorithmBuffer.BufferType = BufferType.KdfHashAlgorithm;
hashAlgorithmBuffer.pvBuffer = hashAlgorithmString;
if (pHmacKey != null)
{
- NCryptBuffer hmacKeyBuffer = new NCryptBuffer();
+ NCryptBuffer hmacKeyBuffer = default;
hmacKeyBuffer.cbBuffer = hmacKey.Length;
hmacKeyBuffer.BufferType = BufferType.KdfHmacKey;
hmacKeyBuffer.pvBuffer = new IntPtr(pHmacKey);
if (pSecretPrepend != null)
{
- NCryptBuffer secretPrependBuffer = new NCryptBuffer();
+ NCryptBuffer secretPrependBuffer = default;
secretPrependBuffer.cbBuffer = secretPrepend.Length;
secretPrependBuffer.BufferType = BufferType.KdfSecretPrepend;
secretPrependBuffer.pvBuffer = new IntPtr(pSecretPrepend);
if (pSecretAppend != null)
{
- NCryptBuffer secretAppendBuffer = new NCryptBuffer();
+ NCryptBuffer secretAppendBuffer = default;
secretAppendBuffer.cbBuffer = secretAppend.Length;
secretAppendBuffer.BufferType = BufferType.KdfSecretAppend;
secretAppendBuffer.pvBuffer = new IntPtr(pSecretAppend);
{
fixed (NCryptBuffer* pParameters = &MemoryMarshal.GetReference(parameters))
{
- NCryptBufferDesc parameterDesc = new NCryptBufferDesc();
+ NCryptBufferDesc parameterDesc = default;
parameterDesc.ulVersion = 0;
parameterDesc.cBuffers = parameters.Length;
parameterDesc.pBuffers = new IntPtr(pParameters);
{
fixed (byte* pLabel = label, pSeed = seed)
{
- NCryptBuffer labelBuffer = new NCryptBuffer();
+ NCryptBuffer labelBuffer = default;
labelBuffer.cbBuffer = label.Length;
labelBuffer.BufferType = BufferType.KdfTlsLabel;
labelBuffer.pvBuffer = new IntPtr(pLabel);
buffers[0] = labelBuffer;
- NCryptBuffer seedBuffer = new NCryptBuffer();
+ NCryptBuffer seedBuffer = default;
seedBuffer.cbBuffer = seed.Length;
seedBuffer.BufferType = BufferType.KdfTlsSeed;
seedBuffer.pvBuffer = new IntPtr(pSeed);
internal static unsafe int RtlGetVersionEx(out RTL_OSVERSIONINFOEX osvi)
{
- osvi = new RTL_OSVERSIONINFOEX();
+ osvi = default;
osvi.dwOSVersionInfoSize = (uint)sizeof(RTL_OSVERSIONINFOEX);
return RtlGetVersion(ref osvi);
}
}
}
- Sec_Application_Protocols protocols = new Sec_Application_Protocols();
+ Sec_Application_Protocols protocols = default;
int protocolListConstSize = sizeof(Sec_Application_Protocols) - sizeof(uint) /* offsetof(Sec_Application_Protocols, ProtocolExtensionType) */;
protocols.ProtocolListsSize = (uint)(protocolListConstSize + protocolListSize);
refHandle = SafeFreeContextBufferChannelBinding.CreateEmptyHandle();
// Bindings is on the stack, so there's no need for a fixed block.
- SecPkgContext_Bindings bindings = new SecPkgContext_Bindings();
+ SecPkgContext_Bindings bindings = default;
return SafeFreeContextBufferChannelBinding.QueryContextChannelBinding(phContext, attribute, &bindings, refHandle);
}
protected SafeDeleteContext() : base(IntPtr.Zero, true)
{
- _handle = new Interop.SspiCli.CredHandle();
+ _handle = default;
}
public override bool IsInvalid
protected SafeFreeCredentials() : base(IntPtr.Zero, true)
{
- _handle = new Interop.SspiCli.CredHandle();
+ _handle = default;
}
#if TRACE_VERBOSE
private static bool DirectoryExists(string path, out int lastError)
{
- Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA();
+ Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
lastError = FillAttributeInfo(path, ref data, returnErrorOnNotFound: true);
return
public static bool FileExists(string fullPath)
{
- Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA();
+ Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true);
return
// pagefile.sys case. As such we're probably stuck filtering out specific
// cases that we know we don't want to retry on.
- var findData = new Interop.Kernel32.WIN32_FIND_DATA();
+ Interop.Kernel32.WIN32_FIND_DATA findData = default;
using (SafeFindHandle handle = Interop.Kernel32.FindFirstFile(path, ref findData))
{
if (handle.IsInvalid)
// can benefit from the synchronization of _intCompleted). That means you can get here before _result got
// set (although rarely - once every eight hours of stress). Handle that case with a spin-lock.
- SpinWait sw = new SpinWait();
+ SpinWait sw = default;
while (_result == DBNull.Value)
{
sw.SpinOnce();
{
uint size = 0;
SafeLocalAllocHandle buffer = null;
- Interop.IpHlpApi.FIXED_INFO fixedInfo = new Interop.IpHlpApi.FIXED_INFO();
+ Interop.IpHlpApi.FIXED_INFO fixedInfo = default;
// First we need to get the size of the buffer
uint result = Interop.IpHlpApi.GetNetworkParams(SafeLocalAllocHandle.InvalidHandle, ref size);
{
Debug.Assert(_receiveBufferCount >= 2, $"Expected to at least have the first two bytes of the header.");
- var header = new MessageHeader();
+ MessageHeader header = default;
Span<byte> receiveBufferSpan = _receiveBuffer.Span;
header.Fin = (receiveBufferSpan[_receiveBufferOffset] & 0x80) != 0;
unsafe
{
- DSAParameters dsaParams = new DSAParameters();
+ DSAParameters dsaParams = default;
fixed (byte* pDsaBlob = dsaBlob)
{
{
BCRYPT_ECCFULLKEY_BLOB* pBcryptBlob = (BCRYPT_ECCFULLKEY_BLOB*)pEcBlob;
- var primeCurve = new ECCurve();
+ ECCurve primeCurve = default;
primeCurve.CurveType = ConvertToCurveTypeEnum(pBcryptBlob->CurveType);
primeCurve.Hash = GetHashAlgorithmName(pBcryptBlob->CurveGenerationAlgId);
using (SafeUnicodeStringHandle safeCurveName = new SafeUnicodeStringHandle(curveName))
{
- var desc = new Interop.BCrypt.BCryptBufferDesc();
- var buff = new Interop.BCrypt.BCryptBuffer();
+ Interop.BCrypt.BCryptBufferDesc desc = default;
+ Interop.BCrypt.BCryptBuffer buff = default;
IntPtr descPtr = IntPtr.Zero;
IntPtr buffPtr = IntPtr.Zero;
try
{
- ECParameters ecparams = new ECParameters();
+ ECParameters ecparams = default;
ECCng.ExportPrimeCurveParameters(ref ecparams, blob, includePrivateParameters);
return ecparams;
}
public override ECParameters ExportParameters(bool includePrivateParameters)
{
- ECParameters ecparams = new ECParameters();
+ ECParameters ecparams = default;
string curveName = GetCurveName(out string oidValue);
byte[] blob = null;
public override ECParameters ExportExplicitParameters(bool includePrivateParameters)
{
byte[] blob = ExportFullKeyBlob(includePrivateParameters);
- ECParameters ecparams = new ECParameters();
+ ECParameters ecparams = default;
ECCng.ExportPrimeCurveParameters(ref ecparams, blob, includePrivateParameters);
return ecparams;
}
/// <returns>The key and named curve parameters used by the ECC object.</returns>
public override ECParameters ExportParameters(bool includePrivateParameters)
{
- ECParameters ecparams = new ECParameters();
+ ECParameters ecparams = default;
string curveName = GetCurveName(out string oidValue);
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
byte[] rsaBlob = ExportKeyBlob(includePrivateParameters);
- RSAParameters rsaParams = new RSAParameters();
+ RSAParameters rsaParams = default;
ExportParameters(ref rsaParams, rsaBlob, includePrivateParameters);
return rsaParams;
}
int piarg = 0;
int cargUnique = 0;
- UserStringBuilder builder = new UserStringBuilder();
+ UserStringBuilder builder = default;
for (int iarg = 0; iarg < args.Length; iarg++)
{
s_isUserInteractive = true;
int lengthNeeded = 0;
- Interop.User32.USEROBJECTFLAGS flags = new Interop.User32.USEROBJECTFLAGS();
+ Interop.User32.USEROBJECTFLAGS flags = default;
if (Interop.User32.GetUserObjectInformationW(hwinsta, Interop.User32.UOI_FLAGS, ref flags, sizeof(Interop.User32.USEROBJECTFLAGS), ref lengthNeeded))
{
if (_windowHandle != IntPtr.Zero)
{
- Interop.User32.MSG msg = new Interop.User32.MSG();
+ Interop.User32.MSG msg = default(Interop.User32.MSG);
bool keepRunning = true;
#if DEBUG
bool tryAddReturnValue =
#endif
- TryAddWithNoTimeValidation(item, Timeout.Infinite, new CancellationToken());
+ TryAddWithNoTimeValidation(item, Timeout.Infinite, CancellationToken.None);
#if DEBUG
Debug.Assert(tryAddReturnValue, "TryAdd() was expected to return true.");
#endif
/// <exception cref="System.InvalidOperationException">The underlying collection didn't accept the item.</exception>
public bool TryAdd(T item)
{
- return TryAddWithNoTimeValidation(item, 0, new CancellationToken());
+ return TryAddWithNoTimeValidation(item, 0, CancellationToken.None);
}
/// <summary>
public bool TryAdd(T item, TimeSpan timeout)
{
ValidateTimeout(timeout);
- return TryAddWithNoTimeValidation(item, (int)timeout.TotalMilliseconds, new CancellationToken());
+ return TryAddWithNoTimeValidation(item, (int)timeout.TotalMilliseconds, CancellationToken.None);
}
/// <summary>
public bool TryAdd(T item, int millisecondsTimeout)
{
ValidateMillisecondsTimeout(millisecondsTimeout);
- return TryAddWithNoTimeValidation(item, millisecondsTimeout, new CancellationToken());
+ return TryAddWithNoTimeValidation(item, millisecondsTimeout, CancellationToken.None);
}
/// <summary>
// spins until all adders finish then throw IOE
// The idea behind to spin until all adders finish, is to avoid to return to the caller with IOE while there are still some adders have
// not been finished yet
- SpinWait spinner = new SpinWait();
+ SpinWait spinner = default;
while (true)
{
int observedAdders = _currentAdders;
if (IsAddingCompleted)
return;
- SpinWait spinner = new SpinWait();
+ SpinWait spinner = default;
while (true)
{
int observedAdders = _currentAdders;
{
if (queue._currentOp != (int)Operation.None)
{
- var spinner = new SpinWait();
+ SpinWait spinner = default;
do { spinner.SpinOnce(); }
while (queue._currentOp != (int)Operation.None);
}
// steal operations happening at the time.
if ((head - (_tailIndex - 2) >= 0) && _currentOp == (int)Operation.Add)
{
- var spinner = new SpinWait();
+ SpinWait spinner = default;
do
{
spinner.SpinOnce();
/// <param name="tail">The tail pointer to the new list</param>
private void PushCore(Node head, Node tail)
{
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
// Keep trying to CAS the existing head with the new node until we succeed.
do
/// the <see cref="ConcurrentStack{T}"/>.</returns>
private int TryPopCore(int count, out Node? poppedHead)
{
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
// Try to CAS the head with its current next. We stop when we succeed or
// when we notice that the stack is empty, whichever comes first.
// we need to make sure all array copiers are finished
if (_activeCopiers > 0)
{
- SpinWait sw = new SpinWait();
+ SpinWait sw = default;
while (_activeCopiers > 0) sw.SpinOnce();
}
if (_additionalElements.IsEmpty)
{
result = OperationResult.SizeChanged;
- return new HashBucket();
+ return default;
}
else
{
if (_additionalElements.IsEmpty)
{
result = OperationResult.SizeChanged;
- return new HashBucket();
+ return default;
}
else
{
{
List<IEnumerable<CompositionError>> paths = new List<IEnumerable<CompositionError>>();
- VisitContext context = new VisitContext();
+ VisitContext context = default;
context.Path = new Stack<CompositionError>();
context.LeafVisitor = path =>
{
{
internal struct CompositionResult
{
- public static readonly CompositionResult SucceededResult = new CompositionResult();
+ public static readonly CompositionResult SucceededResult;
private readonly IEnumerable<CompositionError> _errors;
public CompositionResult(params CompositionError[] errors)
/// </summary>
public readonly struct MemberRelationship
{
- public static readonly MemberRelationship Empty = new MemberRelationship();
+ public static readonly MemberRelationship Empty;
/// <summary>
/// Creates a new member relationship.
culture = CultureInfo.CurrentCulture;
}
- _flagState = new BitVector32();
+ _flagState = default;
// read only property-backend fields.
internal BaseConfigurationRecord()
{
// not strictly necessary, but compiler spits out a warning without this initiailization
- _flags = new SafeBitVector32();
+ _flags = default;
}
protected abstract SimpleBitVector32 ClassFlags { get; }
// The conversion is true -> OverrideMode.Inherit
// The conversion is false -> OverrideMode.Deny
// This is consistent with Whidbey where true means true unless there is a false somewhere above
- OverrideModeSetting result = new OverrideModeSetting();
+ OverrideModeSetting result = default;
result.SetMode(allowOverride ? OverrideMode.Inherit : OverrideMode.Deny);
result._mode |= XmlDefinedLegacy;
internal static OverrideModeSetting CreateFromXmlReadValue(OverrideMode mode)
{
- OverrideModeSetting result = new OverrideModeSetting();
+ OverrideModeSetting result = default;
result.SetMode(mode);
result._mode |= XmlDefinedNewMode;
_flags[FlagInheritInChildApps] = true;
_flags[FlagForceSave] = false;
- _modifiedFlags = new SimpleBitVector32();
+ _modifiedFlags = default;
}
private bool IsRuntime => _flags[FlagAttached] &&
internal void ResetModifiedFlags()
{
- _modifiedFlags = new SimpleBitVector32();
+ _modifiedFlags = default;
}
internal bool IsModifiedFlags()
if (_cachedInputRecord.eventType == Interop.KEY_EVENT)
return true;
- Interop.InputRecord ir = new Interop.InputRecord();
+ Interop.InputRecord ir = default;
int numEventsRead = 0;
while (true)
{
Interop.Kernel32.CHAR_INFO[] data = new Interop.Kernel32.CHAR_INFO[sourceWidth * sourceHeight];
bufferSize.X = (short)sourceWidth;
bufferSize.Y = (short)sourceHeight;
- Interop.Kernel32.COORD bufferCoord = new Interop.Kernel32.COORD();
- Interop.Kernel32.SMALL_RECT readRegion = new Interop.Kernel32.SMALL_RECT();
+ Interop.Kernel32.COORD bufferCoord = default;
+ Interop.Kernel32.SMALL_RECT readRegion = default;
readRegion.Left = (short)sourceLeft;
readRegion.Right = (short)(sourceLeft + sourceWidth - 1);
readRegion.Top = (short)sourceTop;
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
// Overwrite old section
- Interop.Kernel32.COORD writeCoord = new Interop.Kernel32.COORD();
+ Interop.Kernel32.COORD writeCoord = default;
writeCoord.X = (short)sourceLeft;
Interop.Kernel32.Color c = ConsoleColorToColorAttribute(sourceBackColor, true);
c |= ConsoleColorToColorAttribute(sourceForeColor, false);
}
// Write text to new location
- Interop.Kernel32.SMALL_RECT writeRegion = new Interop.Kernel32.SMALL_RECT();
+ Interop.Kernel32.SMALL_RECT writeRegion = default;
writeRegion.Left = (short)targetLeft;
writeRegion.Right = (short)(targetLeft + sourceWidth);
writeRegion.Top = (short)targetTop;
public static void Clear()
{
- Interop.Kernel32.COORD coordScreen = new Interop.Kernel32.COORD();
+ Interop.Kernel32.COORD coordScreen = default;
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi;
bool success;
int conSize;
public static void SetCursorPosition(int left, int top)
{
IntPtr hConsole = OutputHandle;
- Interop.Kernel32.COORD coords = new Interop.Kernel32.COORD();
+ Interop.Kernel32.COORD coords = default;
coords.X = (short)left;
coords.Y = (short)top;
if (!Interop.Kernel32.SetConsoleCursorPosition(hConsole, coords))
if (height < srWindow.Bottom + 1 || height >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_ConsoleBufferLessThanWindowSize);
- Interop.Kernel32.COORD size = new Interop.Kernel32.COORD();
+ Interop.Kernel32.COORD size = default;
size.X = (short)width;
size.Y = (short)height;
if (!Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, size))
// If the buffer is smaller than this new window size, resize the
// buffer to be large enough. Include window position.
bool resizeBuffer = false;
- Interop.Kernel32.COORD size = new Interop.Kernel32.COORD();
+ Interop.Kernel32.COORD size = default;
size.X = csbi.dwSize.X;
size.Y = csbi.dwSize.Y;
if (csbi.dwSize.X < csbi.srWindow.Left + width)
{
throw new IOException(SR.IO_NoConsole);
}
- return new Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO();
+ return default;
}
// Note that if stdout is redirected to a file, the console handle may be a file.
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE && !throwOnNoConsole)
- return new Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO();
+ return default;
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
else
{
- CancellationTokenRegistration registration = new CancellationTokenRegistration();
+ CancellationTokenRegistration registration = default;
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(s => ((DbCommand)s).CancelIgnoreFailure(), this);
}
else
{
- CancellationTokenRegistration registration = new CancellationTokenRegistration();
+ CancellationTokenRegistration registration = default;
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(s => ((DbCommand)s).CancelIgnoreFailure(), this);
}
else
{
- CancellationTokenRegistration registration = new CancellationTokenRegistration();
+ CancellationTokenRegistration registration = default;
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(s => ((DbCommand)s).CancelIgnoreFailure(), this);
PropertyDescriptor[] props = new PropertyDescriptor[_reader.FieldCount];
for (int i = 0; i < si.Length; i++)
{
- SchemaInfo s = new SchemaInfo();
+ SchemaInfo s = default;
s.name = _reader.GetName(i);
s.type = _reader.GetFieldType(i);
s.typeName = _reader.GetDataTypeName(i);
public override object ConvertXmlToObject(string s)
{
- SqlBinary newValue = new SqlBinary();
+ SqlBinary newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlByte newValue = new SqlByte();
+ SqlByte newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlBinary newValue = new SqlBinary();
+ SqlBinary newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlString newValue = new SqlString();
+ SqlString newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlDateTime newValue = new SqlDateTime();
+ SqlDateTime newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlDecimal newValue = new SqlDecimal();
+ SqlDecimal newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlDouble newValue = new SqlDouble();
+ SqlDouble newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlGuid newValue = new SqlGuid();
+ SqlGuid newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlInt16 newValue = new SqlInt16();
+ SqlInt16 newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlInt32 newValue = new SqlInt32();
+ SqlInt32 newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlInt64 newValue = new SqlInt64();
+ SqlInt64 newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlMoney newValue = new SqlMoney();
+ SqlMoney newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlSingle newValue = new SqlSingle();
+ SqlSingle newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlString newValue = new SqlString();
+ SqlString newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
public override object ConvertXmlToObject(string s)
{
- SqlBoolean newValue = new SqlBoolean();
+ SqlBoolean newValue = default;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataSet.ReadXml|INFO> {0}, denyResolving={1}", ObjectID, denyResolving);
try
{
- DataTable.DSRowDiffIdUsageSection rowDiffIdUsage = new DataTable.DSRowDiffIdUsageSection();
+ DataTable.DSRowDiffIdUsageSection rowDiffIdUsage = default;
try
{
bool fDataFound = false;
return ReadXml(reader);
}
- DataTable.DSRowDiffIdUsageSection rowDiffIdUsage = new DataTable.DSRowDiffIdUsageSection();
+ DataTable.DSRowDiffIdUsageSection rowDiffIdUsage = default;
try
{
bool fSchemaFound = false;
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTable.ReadXml|INFO> {0}, denyResolving={1}", ObjectID, denyResolving);
try
{
- RowDiffIdUsageSection rowDiffIdUsage = new RowDiffIdUsageSection();
+ RowDiffIdUsageSection rowDiffIdUsage = default;
try
{
bool fDataFound = false;
internal XmlReadMode ReadXml(XmlReader reader, XmlReadMode mode, bool denyResolving)
{
- RowDiffIdUsageSection rowDiffIdUsage = new RowDiffIdUsageSection();
+ RowDiffIdUsageSection rowDiffIdUsage = default;
try
{
bool fSchemaFound = false;
int lo = FindFirstMatchingRecord();
if (lo == -1)
{
- return new Range();
+ return default;
}
int hi = FindLastMatchingRecord(lo);
Debug.Assert(lo <= hi, "GetBinaryFilteredRecords : Invalid Search Results");
if (IndexTree.NIL == nodeId)
{
- return new Range();
+ return default;
}
int recordIndex = _records.GetIndexByNode(nodeId);
internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync)
{
// initialize consumer info for MARS
- Sni_Consumer_Info native_consumerInfo = new Sni_Consumer_Info();
+ Sni_Consumer_Info native_consumerInfo = default;
MarshalConsumerInfo(consumerInfo, ref native_consumerInfo);
return SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync);
{
fixed (byte* pin_instanceName = &instanceName[0])
{
- SNI_CLIENT_CONSUMER_INFO clientConsumerInfo = new SNI_CLIENT_CONSUMER_INFO();
+ SNI_CLIENT_CONSUMER_INFO clientConsumerInfo = default;
// initialize client ConsumerInfo part first
MarshalConsumerInfo(consumerInfo, ref clientConsumerInfo.ConsumerInfo);
{
if (_columns.Count <= ordinal)
{
- SmiColumnOrder order = new SmiColumnOrder();
+ SmiColumnOrder order = default;
order.Order = SortOrder.Unspecified;
order.SortOrdinal = -1;
return order;
{
if (_isAsyncBulkCopy)
{
- CancellationTokenRegistration regReconnectCancel = new CancellationTokenRegistration();
+ CancellationTokenRegistration regReconnectCancel = default;
TaskCompletionSource<object> cancellableReconnectTS = new TaskCompletionSource<object>();
if (cts.CanBeCanceled)
{
TaskCompletionSource<int> source = new TaskCompletionSource<int>();
- CancellationTokenRegistration registration = new CancellationTokenRegistration();
+ CancellationTokenRegistration registration = default;
if (cancellationToken.CanBeCanceled)
{
if (cancellationToken.IsCancellationRequested)
TaskCompletionSource<SqlDataReader> source = new TaskCompletionSource<SqlDataReader>();
- CancellationTokenRegistration registration = new CancellationTokenRegistration();
+ CancellationTokenRegistration registration = default;
if (cancellationToken.CanBeCanceled)
{
if (cancellationToken.IsCancellationRequested)
TaskCompletionSource<XmlReader> source = new TaskCompletionSource<XmlReader>();
- CancellationTokenRegistration registration = new CancellationTokenRegistration();
+ CancellationTokenRegistration registration = default;
if (cancellationToken.CanBeCanceled)
{
if (cancellationToken.IsCancellationRequested)
}
else
{
- CancellationTokenRegistration registration = new CancellationTokenRegistration();
+ CancellationTokenRegistration registration = default;
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(s => ((TaskCompletionSource<DbConnectionInternal>)s).TrySetCanceled(), completion);
public static TdsDateTime FromDateTime(DateTime dateTime, byte cb)
{
SqlDateTime sqlDateTime;
- TdsDateTime tdsDateTime = new TdsDateTime();
+ TdsDateTime tdsDateTime = default;
Debug.Assert(cb == 8 || cb == 4, "Invalid date time size!");
private SNIErrorDetails GetSniErrorDetails()
{
- SNIErrorDetails details = new SNIErrorDetails();
+ SNIErrorDetails details = default;
if (TdsParserStateObjectFactory.UseManagedSNI)
{
multiPartTableName = default(MultiPartTableName);
- mpt = new MultiPartTableName();
+ mpt = default;
byte nParts;
// Find out how many parts in the TDS stream
internal NullBitmap Clone()
{
- NullBitmap newBitmap = new NullBitmap();
+ NullBitmap newBitmap = default;
newBitmap._nullBitmap = _nullBitmap == null ? null : (byte[])_nullBitmap.Clone();
newBitmap._columnsCount = _columnsCount;
return newBitmap;
private SNINativeMethodWrapper.ConsumerInfo CreateConsumerInfo(bool async)
{
- SNINativeMethodWrapper.ConsumerInfo myInfo = new SNINativeMethodWrapper.ConsumerInfo();
+ SNINativeMethodWrapper.ConsumerInfo myInfo = default;
Debug.Assert(_outBuff.Length == _inBuff.Length, "Unexpected unequal buffers.");
private const int Flag_disposed = 0x100;
private const int Flag_sourceVerified = 0x200;
- private BitVector32 boolFlags = new BitVector32();
+ private BitVector32 boolFlags;
private Hashtable messageLibraries;
private static readonly Hashtable listenerInfos = new Hashtable(StringComparer.OrdinalIgnoreCase);
_user = user;
_logOnType = logOnType;
- UnsafeNativeMethods.EvtRpcLogin erLogin = new UnsafeNativeMethods.EvtRpcLogin();
+ UnsafeNativeMethods.EvtRpcLogin erLogin = default;
erLogin.Server = _server;
erLogin.User = _user;
erLogin.Domain = _domain;
public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType, object val)
{
- UnsafeNativeMethods.EvtVariant varVal = new UnsafeNativeMethods.EvtVariant();
+ UnsafeNativeMethods.EvtVariant varVal = default;
CoTaskMemSafeHandle taskMem = new CoTaskMemSafeHandle();
return (Interop.Version.VS_FIXEDFILEINFO)Marshal.PtrToStructure<Interop.Version.VS_FIXEDFILEINFO>(memRef);
}
- return new Interop.Version.VS_FIXEDFILEINFO();
+ return default;
}
private static unsafe string GetFileVersionLanguage(IntPtr memPtr)
if (newCounterType == Interop.Kernel32.PerformanceCounterOptions.PERF_ELAPSED_TIME)
return (float)GetElapsedTime(oldSample, newSample);
- Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER newPdhValue = new Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER();
- Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER oldPdhValue = new Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER();
+ Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER newPdhValue = default;
+ Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER oldPdhValue = default;
FillInValues(oldSample, newSample, ref oldPdhValue, ref newPdhValue);
LoadPerfCounterDll();
- Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_COUNTERVALUE pdhFormattedValue = new Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_COUNTERVALUE();
+ Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_COUNTERVALUE pdhFormattedValue = default;
long timeBase = newSample.SystemFrequency;
int result = Interop.PerfCounter.FormatFromRawValue((uint)newCounterType, Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_DOUBLE | Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_NOSCALE | Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_NOCAP100,
ref timeBase, ref newPdhValue, ref oldPdhValue, ref pdhFormattedValue);
out securityDescriptorPointer, IntPtr.Zero))
throw new InvalidOperationException(SR.SetSecurityDescriptorFailed);
- Interop.Kernel32.SECURITY_ATTRIBUTES securityAttributes = new Interop.Kernel32.SECURITY_ATTRIBUTES();
+ Interop.Kernel32.SECURITY_ATTRIBUTES securityAttributes = default;
securityAttributes.bInheritHandle = Interop.BOOL.FALSE;
//
throw new InvalidOperationException(SR.CantMapFileView);
// figure out what size the share memory really is.
- Interop.Kernel32.MEMORY_BASIC_INFORMATION meminfo = new Interop.Kernel32.MEMORY_BASIC_INFORMATION();
+ Interop.Kernel32.MEMORY_BASIC_INFORMATION meminfo = default;
if (Interop.Kernel32.VirtualQuery(_fileViewAddress, ref meminfo, (UIntPtr)sizeof(Interop.Kernel32.MEMORY_BASIC_INFORMATION)) == UIntPtr.Zero)
throw new InvalidOperationException(SR.CantGetMappingSize);
StringBuilder commandLine = BuildCommandLine(startInfo.FileName, StartInfo.Arguments);
Process.AppendArguments(commandLine, StartInfo.ArgumentList);
- Interop.Kernel32.STARTUPINFO startupInfo = new Interop.Kernel32.STARTUPINFO();
- Interop.Kernel32.PROCESS_INFORMATION processInfo = new Interop.Kernel32.PROCESS_INFORMATION();
- Interop.Kernel32.SECURITY_ATTRIBUTES unused_SecAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES();
+ Interop.Kernel32.STARTUPINFO startupInfo = default;
+ Interop.Kernel32.PROCESS_INFORMATION processInfo = default;
+ Interop.Kernel32.SECURITY_ATTRIBUTES unused_SecAttrs = default;
SafeProcessHandle procSH = new SafeProcessHandle();
SafeThreadHandle threadSH = new SafeThreadHandle();
// for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchronously!
private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs)
{
- Interop.Kernel32.SECURITY_ATTRIBUTES securityAttributesParent = new Interop.Kernel32.SECURITY_ATTRIBUTES();
+ Interop.Kernel32.SECURITY_ATTRIBUTES securityAttributesParent = default;
securityAttributesParent.bInheritHandle = Interop.BOOL.TRUE;
SafeFileHandle hTmp = null;
processHandle = ProcessManager.OpenProcess(processId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_VM_READ, true);
IntPtr[] moduleHandles = new IntPtr[64];
- GCHandle moduleHandlesArrayHandle = new GCHandle();
+ GCHandle moduleHandlesArrayHandle = default;
int moduleCount = 0;
while (true)
{
// So we will try to get the privilege here.
// We could fail if the user account doesn't have right to do this, but that's fair.
- Interop.Advapi32.LUID luid = new Interop.Advapi32.LUID();
+ Interop.Advapi32.LUID luid = default;
if (!Interop.Advapi32.LookupPrivilegeValue(null, Interop.Advapi32.SeDebugPrivilege, out luid))
{
return;
try
{
- UnsafeNativeMethods.LUID luid = new UnsafeNativeMethods.LUID();
+ UnsafeNativeMethods.LUID luid = default;
luid.low = 0;
luid.high = 0;
private void DoServerVerifyAndPropRetrieval()
{
- _serverProperties = new ServerProperties();
+ _serverProperties = default;
if (_contextType == ContextType.ApplicationDirectory || _contextType == ContextType.Domain)
{
ReadServerConfig(_name, ref _serverProperties);
public string DomainNameDns;
[MarshalAs(UnmanagedType.LPWStr)]
public string DomainForestName;
- public Guid DomainGuid = new Guid();
+ public Guid DomainGuid;
}
/*
public string DomainControllerName = null;
public string DomainControllerAddress = null;
public int DomainControllerAddressType = 0;
- public Guid DomainGuid = new Guid();
+ public Guid DomainGuid;
public string DomainName = null;
public string DnsForestName = null;
public int Flags = 0;
throw new ObjectDisposedException(GetType().Name);
}
- var tempHandle = new SecurityHandle();
+ SecurityHandle tempHandle = default;
int error = Wldap32.ldap_get_option_sechandle(_connection._ldapHandle, LdapOption.LDAP_OPT_SECURITY_CONTEXT, ref tempHandle);
ErrorChecking.CheckAndSetLdapError(error);
public string DomainNameDns;
[MarshalAs(UnmanagedType.LPWStr)]
public string DomainForestName;
- public Guid DomainGuid = new Guid();
+ public Guid DomainGuid = default;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
}
// the new option is available, set it so we get the new PutEx behavior that will allow multiple changes
- Variant value = new Variant();
+ Variant value = default;
value.varType = 11; //VT_BOOL
value.boolvalue = -1;
((UnsafeNativeMethods.IAdsObjectOptions2)_adsObject).SetOption(8, value);
AdsSearchPreferenceInfo info;
// search scope
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.SEARCH_SCOPE;
info.vValue = new AdsValueHelper((int)SearchScope).GetStruct();
prefList.Add(info);
// size limit
if (_sizeLimit != 0 || !findMoreThanOne)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.SIZE_LIMIT;
info.vValue = new AdsValueHelper(findMoreThanOne ? SizeLimit : 1).GetStruct();
prefList.Add(info);
// time limit
if (ServerTimeLimit >= new TimeSpan(0))
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.TIME_LIMIT;
info.vValue = new AdsValueHelper((int)ServerTimeLimit.TotalSeconds).GetStruct();
prefList.Add(info);
}
// propertyNamesOnly
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.ATTRIBTYPES_ONLY;
info.vValue = new AdsValueHelper(PropertyNamesOnly).GetStruct();
prefList.Add(info);
// Timeout
if (ClientTimeout >= new TimeSpan(0))
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.TIMEOUT;
info.vValue = new AdsValueHelper((int)ClientTimeout.TotalSeconds).GetStruct();
prefList.Add(info);
// page size
if (PageSize != 0)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.PAGESIZE;
info.vValue = new AdsValueHelper(PageSize).GetStruct();
prefList.Add(info);
// page time limit
if (ServerPageTimeLimit >= new TimeSpan(0))
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.PAGED_TIME_LIMIT;
info.vValue = new AdsValueHelper((int)ServerPageTimeLimit.TotalSeconds).GetStruct();
prefList.Add(info);
}
// chase referrals
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.CHASE_REFERRALS;
info.vValue = new AdsValueHelper((int)ReferralChasing).GetStruct();
prefList.Add(info);
// asynchronous
if (Asynchronous == true)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.ASYNCHRONOUS;
info.vValue = new AdsValueHelper(Asynchronous).GetStruct();
prefList.Add(info);
// tombstone
if (Tombstone == true)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.TOMBSTONE;
info.vValue = new AdsValueHelper(Tombstone).GetStruct();
prefList.Add(info);
// attributescopequery
if (_attributeScopeQuerySpecified)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.ATTRIBUTE_QUERY;
info.vValue = new AdsValueHelper(AttributeScopeQuery, AdsType.ADSTYPE_CASE_IGNORE_STRING).GetStruct();
prefList.Add(info);
// derefalias
if (DerefAlias != DereferenceAlias.Never)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.DEREF_ALIASES;
info.vValue = new AdsValueHelper((int)DerefAlias).GetStruct();
prefList.Add(info);
// securitymask
if (SecurityMasks != SecurityMasks.None)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.SECURITY_MASK;
info.vValue = new AdsValueHelper((int)SecurityMasks).GetStruct();
prefList.Add(info);
// extendeddn
if (ExtendedDN != ExtendedDN.None)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.EXTENDED_DN;
info.vValue = new AdsValueHelper((int)ExtendedDN).GetStruct();
prefList.Add(info);
// dirsync
if (directorySynchronizationSpecified)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.DIRSYNC;
info.vValue = new AdsValueHelper(DirectorySynchronization.GetDirectorySynchronizationCookie(), AdsType.ADSTYPE_PROV_SPECIFIC).GetStruct();
prefList.Add(info);
if (DirectorySynchronization.Option != DirectorySynchronizationOptions.None)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.DIRSYNC_FLAG;
info.vValue = new AdsValueHelper((int)DirectorySynchronization.Option).GetStruct();
prefList.Add(info);
// sort
if (Sort.PropertyName != null && Sort.PropertyName.Length > 0)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.SORT_ON;
- AdsSortKey sortKey = new AdsSortKey();
+ AdsSortKey sortKey = default;
sortKey.pszAttrType = Marshal.StringToCoTaskMemUni(Sort.PropertyName);
ptrToFree = sortKey.pszAttrType; // so we can free it later.
sortKey.pszReserved = (IntPtr)0;
// vlv
if (directoryVirtualListViewSpecified)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.VLV;
AdsVLV vlvValue = new AdsVLV();
vlvValue.beforeCount = _vlv.BeforeCount;
// cacheResults
if (_cacheResultsSpecified)
{
- info = new AdsSearchPreferenceInfo();
+ info = default;
info.dwSearchPref = (int)AdsSearchPreferences.CACHE_RESULTS;
info.vValue = new AdsValueHelper(CacheResults).GetStruct();
prefList.Add(info);
throw new ObjectDisposedException(GetType().Name);
// get the dirsync cookie back
- AdsSearchColumn column = new AdsSearchColumn();
+ AdsSearchColumn column = default;
AdsSearchColumn* pColumn = &column;
SearchObject.GetColumn(Handle, _adsDirsynCookieName, (INTPTR_INTPTRCAST)pColumn);
try
throw new ObjectDisposedException(GetType().Name);
// get the vlv response back
- AdsSearchColumn column = new AdsSearchColumn();
+ AdsSearchColumn column = default;
AdsSearchColumn* pColumn = &column;
SearchObject.GetColumn(Handle, _adsVLVResponseName, (INTPTR_INTPTRCAST)pColumn);
try
{
try
{
- AdsSearchColumn column = new AdsSearchColumn();
+ AdsSearchColumn column = default;
AdsSearchColumn* pColumn = &column;
_results.SearchObject.GetColumn(_results.Handle, pszColumnName, (INTPTR_INTPTRCAST)pColumn);
try
}
IntPtr hbmRet = IntPtr.Zero;
- var pbmi = new NativeMethods.BITMAPINFO_FLAT();
+ NativeMethods.BITMAPINFO_FLAT pbmi = default;
// Validate hdc.
Interop.Gdi32.ObjectType objType = Interop.Gdi32.GetObjectType(hdc);
public void AddString(string s, FontFamily family, int style, float emSize, Point origin, StringFormat format)
{
- Rectangle layout = new Rectangle();
+ Rectangle layout = default;
layout.X = origin.X;
layout.Y = origin.Y;
AddString(s, family, style, emSize, layout, format);
public void AddString(string s, FontFamily family, int style, float emSize, PointF origin, StringFormat format)
{
- RectangleF layout = new RectangleF();
+ RectangleF layout = default;
layout.X = origin.X;
layout.Y = origin.Y;
AddString(s, family, style, emSize, layout, format);
IntPtr newObject;
FontStyle newStyle = FontStyle.Regular;
float newSize;
- Interop.User32.LOGFONT lf = new Interop.User32.LOGFONT();
+ Interop.User32.LOGFONT lf = default;
// Sanity. Should we throw an exception?
if (hfont == IntPtr.Zero)
/// </summary>
public static Font FromHfont(IntPtr hfont)
{
- var logFont = new Interop.User32.LOGFONT();
+ Interop.User32.LOGFONT logFont = default;
SafeNativeMethods.GetObject(new HandleRef(null, hfont), ref logFont);
using (ScreenDC dc = ScreenDC.Create())
}
// Now that we know the marshalled size is the same as LOGFONT, copy in the data
- logFont = new Interop.User32.LOGFONT();
+ logFont = default;
Marshal.StructureToPtr(lf, new IntPtr(&logFont), fDeleteOld: false);
throw new ArgumentNullException(nameof(graphics));
}
- Interop.User32.LOGFONT logFont = new Interop.User32.LOGFONT();
+ Interop.User32.LOGFONT logFont = default;
Gdip.CheckStatus(Gdip.GdipGetLogFontW(
new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), ref logFont));
public static StartupInput GetDefault()
{
- StartupInput result = new StartupInput();
+ StartupInput result = default;
result.GdiplusVersion = 1;
// result.DebugEventCallback = null;
result.SuppressBackgroundThread = false;
window = LibX11Functions.XRootWindow(Gdip.Display, 0);
defvisual = LibX11Functions.XDefaultVisual(Gdip.Display, 0);
- XVisualInfo visual = new XVisualInfo();
+ XVisualInfo visual = default;
/* Get XVisualInfo for this visual */
visual.visualid = LibX11Functions.XVisualIDFromVisual(defvisual);
throw new ArgumentNullException(nameof(font));
RectangleF layout = new RectangleF(0, 0, layoutArea.Width, layoutArea.Height);
- RectangleF boundingBox = new RectangleF();
+ RectangleF boundingBox = default;
Gdip.CheckStatus(Gdip.GdipMeasureString(
new HandleRef(this, NativeGraphics),
throw new ArgumentNullException(nameof(font));
RectangleF layout = new RectangleF(origin.X, origin.Y, 0, 0);
- RectangleF boundingBox = new RectangleF();
+ RectangleF boundingBox = default;
Gdip.CheckStatus(Gdip.GdipMeasureString(
new HandleRef(this, NativeGraphics),
throw new ArgumentNullException(nameof(font));
RectangleF layout = new RectangleF(0, 0, layoutArea.Width, layoutArea.Height);
- RectangleF boundingBox = new RectangleF();
+ RectangleF boundingBox = default;
Gdip.CheckStatus(Gdip.GdipMeasureString(
new HandleRef(this, NativeGraphics),
writer.Write((ushort)1); // only one icon
// when transformed into a bitmap only a single image exists
- IconDirEntry ide = new IconDirEntry();
+ IconDirEntry ide = default;
ide.width = (byte)bitmap.Width;
ide.height = (byte)bitmap.Height;
ide.colorCount = 0; // 32 bbp == 0, for palette size
ide.bitCount = 32;
ide.imageOffset = 22; // 22 is the first icon position (for single icon files)
- BitmapInfoHeader bih = new BitmapInfoHeader();
+ BitmapInfoHeader bih = default;
bih.biSize = (uint)Marshal.SizeOf(typeof(BitmapInfoHeader));
bih.biWidth = bitmap.Width;
bih.biHeight = 2 * bitmap.Height; // include both XOR and AND images
{
if (_iconSize.IsEmpty)
{
- var info = new SafeNativeMethods.ICONINFO();
+ SafeNativeMethods.ICONINFO info = default;
SafeNativeMethods.GetIconInfo(new HandleRef(this, Handle), ref info);
- var bitmap = new SafeNativeMethods.BITMAP();
+ SafeNativeMethods.BITMAP bitmap = default;
if (info.hbmColor != IntPtr.Zero)
{
else if (_bestBitDepth == 0 || _bestBitDepth == 32)
{
// This may be a 32bpp icon or an icon without any data.
- var info = new SafeNativeMethods.ICONINFO();
+ SafeNativeMethods.ICONINFO info = default;
SafeNativeMethods.GetIconInfo(new HandleRef(this, _handle), ref info);
- var bmp = new SafeNativeMethods.BITMAP();
+ SafeNativeMethods.BITMAP bmp = default;
try
{
if (info.hbmColor != IntPtr.Zero)
int propSize;
IntPtr property;
PropertyItem item = new PropertyItem();
- GdipPropertyItem gdipProperty = new GdipPropertyItem();
+ GdipPropertyItem gdipProperty = default;
int status;
status = Gdip.GdipGetPropertyItemSize(nativeImage, propid,
IntPtr dest = Marshal.AllocHGlobal(size);
try
{
- GdipPropertyItem pi = new GdipPropertyItem();
+ GdipPropertyItem pi = default;
pi.id = propitem.Id;
pi.len = propitem.Len;
pi.type = propitem.Type;
int propNums, propsSize, propSize;
IntPtr properties, propPtr;
PropertyItem[] items;
- GdipPropertyItem gdipProperty = new GdipPropertyItem();
+ GdipPropertyItem gdipProperty = default;
int status;
status = Gdip.GdipGetPropertySize(nativeImage, out propsSize, out propNums);
{
get
{
- Guid guid = new Guid();
+ Guid guid = default;
int status = Gdip.GdipGetImageRawFormat(new HandleRef(this, nativeImage), ref guid);
Gdip.CheckStatus(status);
// writer queue. See ReaderWriterLock.AcquireWriterLock method in the MSDN.
bool readerLockHeld = s_rwImgListLock.IsReaderLockHeld;
- LockCookie lockDowngradeCookie = new LockCookie();
+ LockCookie lockDowngradeCookie = default;
t_threadWriterLockWaitCount++;
// Acquire a writer lock to modify the image info list - See comments on Animate() about this locking.
bool readerLockHeld = s_rwImgListLock.IsReaderLockHeld;
- LockCookie lockDowngradeCookie = new LockCookie();
+ LockCookie lockDowngradeCookie = default;
t_threadWriterLockWaitCount++;
/// </summary>
public ColorMap()
{
- _oldColor = new Color();
- _newColor = new Color();
}
/// <summary>
public void SetWrapMode(WrapMode mode)
{
- SetWrapMode(mode, new Color(), false);
+ SetWrapMode(mode, default(Color), false);
}
public void SetWrapMode(WrapMode mode, Color color)
}
public Metafile(IntPtr referenceHdc, EmfType emfType, string description) :
- this(referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, emfType, description)
+ this(referenceHdc, default(RectangleF), MetafileFrameUnit.GdiCompatible, emfType, description)
{
}
public Metafile(Stream stream, IntPtr referenceHdc, EmfType type, string description) :
- this(stream, referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, type, description)
+ this(stream, referenceHdc, default(RectangleF), MetafileFrameUnit.GdiCompatible, type, description)
{
}
public Metafile(string fileName, IntPtr referenceHdc, EmfType type, string description) :
- this(fileName, referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, type, description)
+ this(fileName, referenceHdc, default(RectangleF), MetafileFrameUnit.GdiCompatible, type, description)
{
}
if (this.MetafileSize == 0)
{
// GDI+ compatibility;
- return new Rectangle();
+ return default;
}
return new Rectangle(header.x, header.y, header.width, header.height);
{
get
{
- RectangleF printableArea = new RectangleF();
+ RectangleF printableArea = default;
DeviceContext dc = printerSettings.CreateInformationContext(this);
HandleRef hdc = new HandleRef(dc, dc.Hdc);
default_page_settings.PrinterResolution.X,
default_page_settings.PrinterResolution.Y, ref graphics);
- DOCINFO doc = new DOCINFO();
+ DOCINFO doc = default;
doc.filename = name;
doc.settings = settings;
doc.default_page_settings = default_page_settings;
{
Font iconTitleFont = null;
- var itfont = new Interop.User32.LOGFONT();
+ Interop.User32.LOGFONT itfont = default;
if (Interop.User32.SystemParametersInfoW(Interop.User32.SystemParametersAction.SPI_GETICONTITLELOGFONT, (uint)sizeof(Interop.User32.LOGFONT), &itfont, 0))
{
iconTitleFont = GetFontFromData(itfont);
{
IntPtr graphicsContext = objc_msgSend(objc_getClass("NSGraphicsContext"), sel_registerName("currentContext"));
IntPtr ctx = objc_msgSend(graphicsContext, sel_registerName("graphicsPort"));
- Rect bounds = new Rect();
+ Rect bounds = default;
CGContextSaveGState(ctx);
return new CarbonContext(port, context, (int)desktop_bounds.size.width, (int)desktop_bounds.size.height);
}
- QDRect window_bounds = new QDRect();
- Rect view_bounds = new Rect();
+ QDRect window_bounds = default(QDRect);
+ Rect view_bounds = default(Rect);
port = GetWindowPort(window);
/// </summary>
public void TranslateTransform(int dx, int dy)
{
- var origin = new Point();
+ Point origin = default;
Interop.Gdi32.OffsetViewportOrgEx(new HandleRef(this, _hDC), dx, dy, ref origin);
}
return new Rectangle(-int.MaxValue, -int.MaxValue, int.MaxValue, int.MaxValue);
}
- var rect = new Interop.Gdi32.RECT();
+ Interop.Gdi32.RECT rect = default;
Interop.Gdi32.GetRgnBox(new HandleRef(this, _nativeHandle), ref rect);
return new Rectangle(new Point(rect.left, rect.top), rect.Size);
}
[TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public readonly struct Color : IEquatable<Color>
{
- public static readonly Color Empty = new Color();
+ public static readonly Color Empty;
// -------------------------------------------------------------------
// static list of "web" colors...
/// <summary>
/// Creates a new instance of the <see cref='System.Drawing.Point'/> class with member data left uninitialized.
/// </summary>
- public static readonly Point Empty = new Point();
+ public static readonly Point Empty;
private int x; // Do not rename (binary serialization)
private int y; // Do not rename (binary serialization)
/// <summary>
/// Creates a new instance of the <see cref='System.Drawing.PointF'/> class with member data left uninitialized.
/// </summary>
- public static readonly PointF Empty = new PointF();
+ public static readonly PointF Empty;
private float x; // Do not rename (binary serialization)
private float y; // Do not rename (binary serialization)
[TypeConverter("System.Drawing.RectangleConverter, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public struct Rectangle : IEquatable<Rectangle>
{
- public static readonly Rectangle Empty = new Rectangle();
+ public static readonly Rectangle Empty;
private int x; // Do not rename (binary serialization)
private int y; // Do not rename (binary serialization)
/// <summary>
/// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> class.
/// </summary>
- public static readonly RectangleF Empty = new RectangleF();
+ public static readonly RectangleF Empty;
private float x; // Do not rename (binary serialization)
private float y; // Do not rename (binary serialization)
/// <summary>
/// Initializes a new instance of the <see cref='System.Drawing.Size'/> class.
/// </summary>
- public static readonly Size Empty = new Size();
+ public static readonly Size Empty;
private int width; // Do not rename (binary serialization)
private int height; // Do not rename (binary serialization)
/// <summary>
/// Initializes a new instance of the <see cref='System.Drawing.SizeF'/> class.
/// </summary>
- public static readonly SizeF Empty = new SizeF();
+ public static readonly SizeF Empty;
private float width; // Do not rename (binary serialization)
private float height; // Do not rename (binary serialization)
public ZLibStreamHandle()
: base(new IntPtr(-1), true)
{
- _zStream = new ZStream();
_zStream.Init();
_initializationState = State.NotInitialized;
Debug.Assert(_storedEntryNameBytes.Length <= ushort.MaxValue);
// decide if we need the Zip64 extra field:
- Zip64ExtraField zip64ExtraField = new Zip64ExtraField();
+ Zip64ExtraField zip64ExtraField = default;
uint compressedSizeTruncated, uncompressedSizeTruncated, offsetOfLocalHeaderTruncated;
bool zip64Needed = false;
Debug.Assert(_storedEntryNameBytes.Length <= ushort.MaxValue);
// decide if we need the Zip64 extra field:
- Zip64ExtraField zip64ExtraField = new Zip64ExtraField();
+ Zip64ExtraField zip64ExtraField = default;
bool zip64Used = false;
uint compressedSizeTruncated, uncompressedSizeTruncated;
// assumes we are positioned at the beginning of an extra field subfield
public static bool TryReadBlock(BinaryReader reader, long endExtraField, out ZipGenericExtraField field)
{
- field = new ZipGenericExtraField();
+ field = default;
// not enough bytes to read tag + size
if (endExtraField - reader.BaseStream.Position < 4)
}
}
- zip64Field = new Zip64ExtraField();
+ zip64Field = default;
zip64Field._compressedSize = null;
zip64Field._uncompressedSize = null;
bool readLocalHeaderOffset, bool readStartDiskNumber,
out Zip64ExtraField zip64Block)
{
- zip64Block = new Zip64ExtraField();
+ zip64Block = default;
zip64Block._compressedSize = null;
zip64Block._uncompressedSize = null;
bool readUncompressedSize, bool readCompressedSize,
bool readLocalHeaderOffset, bool readStartDiskNumber)
{
- Zip64ExtraField zip64Field = new Zip64ExtraField();
+ Zip64ExtraField zip64Field = default;
zip64Field._compressedSize = null;
zip64Field._uncompressedSize = null;
public static bool TryReadBlock(BinaryReader reader, out Zip64EndOfCentralDirectoryLocator zip64EOCDLocator)
{
- zip64EOCDLocator = new Zip64EndOfCentralDirectoryLocator();
+ zip64EOCDLocator = default;
if (reader.ReadUInt32() != SignatureConstant)
return false;
public static bool TryReadBlock(BinaryReader reader, out Zip64EndOfCentralDirectoryRecord zip64EOCDRecord)
{
- zip64EOCDRecord = new Zip64EndOfCentralDirectoryRecord();
+ zip64EOCDRecord = default;
if (reader.ReadUInt32() != SignatureConstant)
return false;
// in either case, the zip64 extra field info will be incorporated into other fields
public static bool TryReadBlock(BinaryReader reader, bool saveExtraFieldsAndComments, out ZipCentralDirectoryFileHeader header)
{
- header = new ZipCentralDirectoryFileHeader();
+ header = default;
if (reader.ReadUInt32() != SignatureConstant)
return false;
public static bool TryReadBlock(BinaryReader reader, out ZipEndOfCentralDirectoryBlock eocdBlock)
{
- eocdBlock = new ZipEndOfCentralDirectoryBlock();
+ eocdBlock = default;
if (reader.ReadUInt32() != SignatureConstant)
return false;
// We'll only suppress the media insertion prompt on the topmost directory as that is the
// most likely scenario and we don't want to take the perf hit for large enumerations.
// (We weren't consistent with how we handled this historically.)
- using (new DisableMediaInsertionPrompt())
+ using (default(DisableMediaInsertionPrompt))
{
// We need to initialize the directory handle up front to ensure
// we immediately throw IO exceptions for missing directory/etc.
public static FileAttributes GetAttributes(string fullPath)
{
- Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA();
+ Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
public static DateTimeOffset GetCreationTime(string fullPath)
{
- Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA();
+ Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
public static DateTimeOffset GetLastAccessTime(string fullPath)
{
- Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA();
+ Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
public static DateTimeOffset GetLastWriteTime(string fullPath)
{
- Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA();
+ Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
return;
}
- Interop.Kernel32.WIN32_FIND_DATA findData = new Interop.Kernel32.WIN32_FIND_DATA();
+ Interop.Kernel32.WIN32_FIND_DATA findData = default;
GetFindData(fullPath, ref findData);
if (IsNameSurrogateReparsePoint(ref findData))
{
{
if (_dataInitialized == -1)
{
- _data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA();
+ _data = default;
Refresh();
}
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
- secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES();
+ secAttrs = default;
secAttrs.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES);
secAttrs.bInheritHandle = Interop.BOOL.TRUE;
}
}
// Query the view for its size and allocation type
- Interop.Kernel32.MEMORY_BASIC_INFORMATION viewInfo = new Interop.Kernel32.MEMORY_BASIC_INFORMATION();
+ Interop.Kernel32.MEMORY_BASIC_INFORMATION viewInfo = default;
Interop.Kernel32.VirtualQuery(viewHandle, ref viewInfo, (UIntPtr)Marshal.SizeOf(viewInfo));
ulong viewSize = (ulong)viewInfo.RegionSize;
throw Win32Marshal.GetExceptionForWin32Error(lastError);
}
// again query the view for its new size
- viewInfo = new Interop.Kernel32.MEMORY_BASIC_INFORMATION();
+ viewInfo = default;
Interop.Kernel32.VirtualQuery(viewHandle, ref viewInfo, (UIntPtr)Marshal.SizeOf(viewInfo));
viewSize = (ulong)viewInfo.RegionSize;
}
if (error != Interop.Errors.ERROR_LOCK_VIOLATION)
throw Win32Marshal.GetExceptionForWin32Error(error);
- SpinWait spinWait = new SpinWait();
+ SpinWait spinWait = default;
for (int w = 0; w < MaxFlushWaits; w++)
{
int pause = (1 << w); // MaxFlushRetries should never be over 30
// If the writer is completed (which it will be most of the time) then return a completed ValueTask
if (_writerAwaitable.IsCompleted)
{
- var flushResult = new FlushResult();
+ FlushResult flushResult = default;
GetFlushResult(ref flushResult);
result = new ValueTask<FlushResult>(flushResult);
}
return new ReadResult(buffer: default, isCanceled: false, isCompleted: true);
}
- var reg = new CancellationTokenRegistration();
+ CancellationTokenRegistration reg = default;
if (cancellationToken.CanBeCanceled)
{
reg = cancellationToken.UnsafeRegister(state => ((StreamPipeReader)state!).Cancel(), this);
return true;
}
- result = new ReadResult();
+ result = default;
return false;
}
{
// Write all completed segments and whatever remains in the current segment
// and flush the result.
- var reg = new CancellationTokenRegistration();
+ CancellationTokenRegistration reg = default;
if (cancellationToken.CanBeCanceled)
{
reg = cancellationToken.UnsafeRegister(state => ((StreamPipeWriter)state!).Cancel(), this);
SafePipeHandle newServerHandle;
// Create the two pipe handles that make up the anonymous pipe.
- var pinningHandle = new GCHandle();
+ GCHandle pinningHandle = default;
try
{
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, ref pinningHandle);
{
// This is the main connection loop. It will loop until the timeout expires.
int elapsed = 0;
- var sw = new SpinWait();
+ SpinWait sw = default;
do
{
cancellationToken.ThrowIfCancellationRequested();
maxNumberOfServerInstances = 255;
}
- var pinningHandle = new GCHandle();
+ GCHandle pinningHandle = default;
try
{
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, ref pinningHandle);
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
- secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES();
+ secAttrs = default;
secAttrs.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES);
secAttrs.bInheritHandle = Interop.BOOL.TRUE;
}
{
if (_handle == null) InternalResources.FileNotOpen();
- SpinWait sw = new SpinWait();
+ SpinWait sw = default;
while (!_writeQueue.IsEmpty)
{
sw.SpinOnce();
// fine for "LPT1" on Win9x, so that alone can't be relied here to
// detect non serial devices.
- _commProp = new Interop.Kernel32.COMMPROP();
+ _commProp = default;
int pinStatus = 0;
if (!Interop.Kernel32.GetCommProperties(_handle, ref _commProp)
if (_commProp.dwMaxBaud != 0 && baudRate > _commProp.dwMaxBaud)
throw new ArgumentOutOfRangeException(nameof(baudRate), SR.Format(SR.Max_Baud, _commProp.dwMaxBaud));
- _comStat = new Interop.Kernel32.COMSTAT();
+ _comStat = default;
// create internal DCB structure, initialize according to Platform SDK
// standard: ms-help://MS.MSNDNQTR.2002APR.1003/hardware/commun_965u.htm
- _dcb = new Interop.Kernel32.DCB();
+ _dcb = default;
// set constant properties of the DCB
InitializeDCB(baudRate, parity, dataBits, stopBits, discardNull);
{
if (_keysAndValues[i].Key == key)
{
- _keysAndValues[i] = new KeyValuePair<TKey, TValue>();
+ _keysAndValues[i] = default;
return;
}
}
// Returns the default settings
internal static QuerySettings Empty
{
- get { return new QuerySettings(null, null, new CancellationToken(), null, null); }
+ get { return new QuerySettings(null, null, CancellationToken.None, null, null); }
}
// Cleanup internal state once the entire query is complete.
Debug.Assert(taskScheduler == TaskScheduler.Default, "PLINQ queries can currently execute only on the default scheduler.");
TraceHelpers.TraceInfo("[timing]: {0}: Queue work {1} to occur asynchronously", DateTime.Now.Ticks, _taskIndex);
- return Task.Factory.StartNew(s_baseWorkDelegate, this, new CancellationToken(), TaskCreationOptions.AttachedToParent | TaskCreationOptions.PreferFairness, taskScheduler);
+ return Task.Factory.StartNew(s_baseWorkDelegate, this, CancellationToken.None, TaskCreationOptions.AttachedToParent | TaskCreationOptions.PreferFairness, taskScheduler);
}
//-----------------------------------------------------------------------------------
Debug.Assert(!_hasOnlyCollections);
var builder = new SparseArrayBuilder<TSource>(initialize: true);
- var deferredCopies = new ArrayBuilder<int>();
+ ArrayBuilder<int> deferredCopies = default;
for (int i = 0; ; i++)
{
public TResult[] ToArray()
{
var builder = new SparseArrayBuilder<TResult>(initialize: true);
- var deferredCopies = new ArrayBuilder<IEnumerable<TResult>>();
+ ArrayBuilder<IEnumerable<TResult>> deferredCopies = default;
foreach (TSource element in _source)
{
// Verify the hostName matches the certificate.
unsafe
{
- var cppStruct = new Interop.Crypt32.CERT_CHAIN_POLICY_PARA();
+ Interop.Crypt32.CERT_CHAIN_POLICY_PARA cppStruct = default;
cppStruct.cbSize = (uint)sizeof(Interop.Crypt32.CERT_CHAIN_POLICY_PARA);
cppStruct.dwFlags = 0;
- var eppStruct = new Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA();
+ Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA eppStruct = default;
eppStruct.cbSize = (uint)sizeof(Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA);
eppStruct.dwAuthType = Interop.Crypt32.AuthType.AUTHTYPE_SERVER;
Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_ALL &
~Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG;
- var status = new Interop.Crypt32.CERT_CHAIN_POLICY_STATUS();
+ Interop.Crypt32.CERT_CHAIN_POLICY_STATUS status = default;
status.cbSize = (uint)sizeof(Interop.Crypt32.CERT_CHAIN_POLICY_STATUS);
if (Interop.Crypt32.CertVerifyCertificateChainPolicy(
(IntPtr)Interop.Crypt32.CertChainPolicy.CERT_CHAIN_POLICY_SSL,
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy)
{
- var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
+ Interop.WinHttp.WINHTTP_PROXY_INFO proxyInfo = default;
bool updateProxySettings = false;
Uri uri = state.RequestMessage.RequestUri;
public WinInetProxyHelper()
{
- var proxyConfig = new Interop.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG();
+ Interop.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig = default;
try
{
public void Initialize(CancellationToken cancellationToken)
{
CancellationToken = cancellationToken;
- var b = new AsyncTaskMethodBuilder();
+ AsyncTaskMethodBuilder b = default;
_ = b.Task; // force initialization
Builder = b;
}
// This lock can be folded into _nextFlushTicks for space optimization, but
// this class should only have a single instance so would rather have clarity.
- private SpinLock _flushLock = new SpinLock();
+ private SpinLock _flushLock = new SpinLock(enableThreadOwnerTracking: false); // mutable struct; do not make this readonly
/// <summary>
/// Checks when a proxy will become usable.
// won't actually discover a PAC file on the network since WPAD protocol isn't configured.
if (_proxyHelper.AutoSettingsUsed && !_proxyHelper.RecentAutoDetectionFailure)
{
- var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
+ Interop.WinHttp.WINHTTP_PROXY_INFO proxyInfo = default;
try
{
if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo))
CFRunLoopStop(runLoop);
};
- var clientContext = new CFStreamClientContext();
+ CFStreamClientContext clientContext = default;
CFRunLoopSourceRef loopSource =
proxy.ProxyType == CFProxy.kCFProxyTypeAutoConfigurationURL ?
CFNetworkExecuteProxyAutoConfigurationURL(proxy.AutoConfigurationURL, cfurl, cb, ref clientContext) :
{
ValidateV2Property(); // CheckDispose and initilize HttpListener in the case of app.config timeouts
- Interop.HttpApi.HTTP_TIMEOUT_LIMIT_INFO timeoutinfo =
- new Interop.HttpApi.HTTP_TIMEOUT_LIMIT_INFO();
+ Interop.HttpApi.HTTP_TIMEOUT_LIMIT_INFO timeoutinfo = default;
timeoutinfo.Flags = Interop.HttpApi.HTTP_FLAGS.HTTP_PROPERTY_FLAG_PRESENT;
timeoutinfo.DrainEntityBody =
// Set the association between request queue and url group. After this, requests for registered urls will
// get delivered to this request queue.
//
- Interop.HttpApi.HTTP_BINDING_INFO info = new Interop.HttpApi.HTTP_BINDING_INFO();
+ Interop.HttpApi.HTTP_BINDING_INFO info = default;
info.Flags = Interop.HttpApi.HTTP_FLAGS.HTTP_PROPERTY_FLAG_PRESENT;
info.RequestQueueHandle = DangerousGetHandle();
// is fine since http.sys allows to set HttpServerBindingProperty multiple times for valid
// Url groups.
//
- Interop.HttpApi.HTTP_BINDING_INFO info = new Interop.HttpApi.HTTP_BINDING_INFO();
+ Interop.HttpApi.HTTP_BINDING_INFO info = default;
info.Flags = Interop.HttpApi.HTTP_FLAGS.NONE;
info.RequestQueueHandle = IntPtr.Zero;
private void SendError(ulong requestId, HttpStatusCode httpStatusCode, ArrayList challenges)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"RequestId: {requestId}");
- Interop.HttpApi.HTTP_RESPONSE httpResponse = new Interop.HttpApi.HTTP_RESPONSE();
- httpResponse.Version = new Interop.HttpApi.HTTP_VERSION();
+ Interop.HttpApi.HTTP_RESPONSE httpResponse = default;
+ httpResponse.Version = default;
httpResponse.Version.MajorVersion = (ushort)1;
httpResponse.Version.MinorVersion = (ushort)1;
httpResponse.StatusCode = (ushort)httpStatusCode;
httpResponse.Headers.UnknownHeaderCount = checked((ushort)(challenges == null ? 0 : challenges.Count));
GCHandle[] challengeHandles = null;
Interop.HttpApi.HTTP_UNKNOWN_HEADER[] headersArray = null;
- GCHandle headersArrayHandle = new GCHandle();
- GCHandle wwwAuthenticateHandle = new GCHandle();
+ GCHandle headersArrayHandle = default;
+ GCHandle wwwAuthenticateHandle = default;
if (httpResponse.Headers.UnknownHeaderCount > 0)
{
challengeHandles = new GCHandle[httpResponse.Headers.UnknownHeaderCount];
{
int oldValue;
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
while ((oldValue = Interlocked.CompareExchange(ref _ownershipState, 1, 0)) == 2)
{
// Must block until it equals 3 - we must be in the callback right now.
{
get
{
- Guid guid = new Guid();
+ Guid guid = default;
*(1 + (ulong*)&guid) = RequestId;
return guid;
}
internal HttpListenerResponse()
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
- _nativeResponse = new Interop.HttpApi.HTTP_RESPONSE();
+ _nativeResponse = default;
_nativeResponse.StatusCode = (ushort)HttpStatusCode.OK;
_nativeResponse.Version.MajorVersion = 1;
_nativeResponse.Version.MinorVersion = 1;
public void CopyFrom(HttpListenerResponse templateResponse)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"templateResponse {templateResponse}");
- _nativeResponse = new Interop.HttpApi.HTTP_RESPONSE();
+ _nativeResponse = default;
_responseState = ResponseState.Created;
_webHeaders = templateResponse._webHeaders;
_boundaryType = templateResponse._boundaryType;
pBuffer = (byte*)pBufferAsIntPtr;
offset = 0;
}
- Interop.HttpApi.HTTP_DATA_CHUNK dataChunk = new Interop.HttpApi.HTTP_DATA_CHUNK();
+ Interop.HttpApi.HTTP_DATA_CHUNK dataChunk = default;
dataChunk.DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
dataChunk.pBuffer = (byte*)(pBuffer + offset);
dataChunk.BufferLength = dataToWrite;
Interop.HttpApi.HTTP_DATA_CHUNK* pDataChunk = null;
if (_httpContext.Response.BoundaryType == BoundaryType.Chunked)
{
- Interop.HttpApi.HTTP_DATA_CHUNK dataChunk = new Interop.HttpApi.HTTP_DATA_CHUNK();
+ Interop.HttpApi.HTTP_DATA_CHUNK dataChunk = default;
dataChunk.DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
dataChunk.pBuffer = (byte*)pBuffer;
dataChunk.BufferLength = (uint)s_chunkTerminator.Length;
{
chunkHeaderBuffer = GetChunkHeader(size, out chunkHeaderOffset);
- _dataChunks[0] = new Interop.HttpApi.HTTP_DATA_CHUNK();
+ _dataChunks[0] = default;
_dataChunks[0].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
_dataChunks[0].BufferLength = (uint)(chunkHeaderBuffer.Length - chunkHeaderOffset);
objectsToPin[0] = chunkHeaderBuffer;
- _dataChunks[1] = new Interop.HttpApi.HTTP_DATA_CHUNK();
+ _dataChunks[1] = default;
_dataChunks[1].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
_dataChunks[1].BufferLength = (uint)size;
objectsToPin[1] = buffer;
- _dataChunks[2] = new Interop.HttpApi.HTTP_DATA_CHUNK();
+ _dataChunks[2] = default;
_dataChunks[2].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
_dataChunks[2].BufferLength = (uint)s_CRLFArray.Length;
}
else
{
- _dataChunks[0] = new Interop.HttpApi.HTTP_DATA_CHUNK();
+ _dataChunks[0] = default;
_dataChunks[0].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
_dataChunks[0].BufferLength = (uint)size;
}
Interop.WebSocket.Buffer payloadBuffer;
- payloadBuffer = new Interop.WebSocket.Buffer();
+ payloadBuffer = default;
_webSocket._internalBuffer.PinSendBuffer(buffer.Value, out _BufferHasBeenPinned);
payloadBuffer.Data.BufferData = _webSocket._internalBuffer.ConvertPinnedSendPayloadToNative(buffer.Value);
payloadBuffer.Data.BufferLength = (uint)buffer.Value.Count;
return null;
}
- Interop.WebSocket.Buffer payloadBuffer = new Interop.WebSocket.Buffer();
+ Interop.WebSocket.Buffer payloadBuffer = default;
if (CloseReason != null)
{
byte[] blob = Encoding.UTF8.GetBytes(CloseReason);
NetEventSource.Enter(this, HttpWebSocket.GetTraceMsgForParameters(offset, count, cancellationToken));
}
- CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
+ CancellationTokenRegistration cancellationTokenRegistration = default;
int bytesRead = 0;
try
NetEventSource.Enter(this);
}
- CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
+ CancellationTokenRegistration cancellationTokenRegistration = default;
try
{
NetEventSource.Enter(this, HttpWebSocket.GetTraceMsgForParameters(offset, count, cancellationToken));
}
- CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
+ CancellationTokenRegistration cancellationTokenRegistration = default;
try
{
NetEventSource.Enter(this);
}
- CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
+ CancellationTokenRegistration cancellationTokenRegistration = default;
try
{
{
_dataChunks = new Interop.HttpApi.HTTP_DATA_CHUNK[2];
_dataChunksGCHandle = GCHandle.Alloc(_dataChunks, GCHandleType.Pinned);
- _dataChunks[0] = new Interop.HttpApi.HTTP_DATA_CHUNK();
+ _dataChunks[0] = default;
_dataChunks[0].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
- _dataChunks[1] = new Interop.HttpApi.HTTP_DATA_CHUNK();
+ _dataChunks[1] = default;
_dataChunks[1].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
}
{
return info[0];
}
- return new LineInfo();
+ return default;
}
internal SmtpReplyReader GetNextReplyReader()
{
return info[0];
}
- return new LineInfo();
+ return default;
}
internal LineInfo[] ReadLines(SmtpReplyReader caller)
{
Debug.Assert(s_dynamicStoreRef == null);
- var storeContext = new Interop.SystemConfiguration.SCDynamicStoreContext();
+ Interop.SystemConfiguration.SCDynamicStoreContext storeContext = default;
using (SafeCreateHandle storeName = Interop.CoreFoundation.CFStringCreateWithCString("NetworkAddressChange.OSX"))
{
s_dynamicStoreRef = Interop.SystemConfiguration.SCDynamicStoreCreate(
/// IP statistics.
internal class SystemIPGlobalStatistics : IPGlobalStatistics
{
- private readonly Interop.IpHlpApi.MibIpStats _stats = new Interop.IpHlpApi.MibIpStats();
+ private readonly Interop.IpHlpApi.MibIpStats _stats = default;
private SystemIPGlobalStatistics() { }
internal static Interop.IpHlpApi.MibIfRow2 GetIfEntry2(long index)
{
- Interop.IpHlpApi.MibIfRow2 ifRow = new Interop.IpHlpApi.MibIfRow2();
+ Interop.IpHlpApi.MibIfRow2 ifRow = default;
if (index == 0)
{
return ifRow;
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(chainContext, cpp.dwFlags);
- var status = new Interop.Crypt32.CERT_CHAIN_POLICY_STATUS();
+ Interop.Crypt32.CERT_CHAIN_POLICY_STATUS status = default;
status.cbSize = (uint)sizeof(Interop.Crypt32.CERT_CHAIN_POLICY_STATUS);
bool errorCode =
else
{
// Other
- _ipPacketInformation = new IPPacketInformation();
+ _ipPacketInformation = default;
}
}
bool canceledOperations = false;
// Wait until it's safe.
- SpinWait sw = new SpinWait();
+ SpinWait sw = default;
while (!_released)
{
// The socket was not released due to the SafeHandle being used.
CancellationRegistration.Dispose();
// Try to transition from Waiting to Cancelled
- var spinWait = new SpinWait();
+ SpinWait spinWait = default;
bool keepWaiting = true;
while (keepWaiting)
{
// The operation could complete so quickly that it races with the code
// initiating it. Wait until that initiation code has completed before
// we try to undo the state it configures.
- var sw = new SpinWait();
+ SpinWait sw = default;
while (_singleBufferHandleState == SingleBufferHandleState.InProcess)
{
sw.SpinOnce();
else
{
// Other.
- _receiveMessageFromPacketInfo = new IPPacketInformation();
+ _receiveMessageFromPacketInfo = default;
}
}
public static unsafe SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption optionValue)
{
- var opt = new Interop.Sys.LingerOption();
+ Interop.Sys.LingerOption opt = default;
Interop.Error err = Interop.Sys.GetLingerOption(handle, &opt);
if (err != Interop.Error.SUCCESS)
{
public static SocketError SetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, MulticastOption optionValue)
{
- Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
+ Interop.Winsock.IPMulticastRequest ipmr = default;
#pragma warning disable CS0618 // Address is marked obsolete
ipmr.MulticastAddress = unchecked((int)optionValue.Group.Address);
public static SocketError SetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, IPv6MulticastOption optionValue)
{
- Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
+ Interop.Winsock.IPv6MulticastRequest ipmr = default;
ipmr.MulticastAddress = optionValue.Group.GetAddressBytes();
ipmr.InterfaceIndex = unchecked((int)optionValue.InterfaceIndex);
public static SocketError SetLingerOption(SafeSocketHandle handle, LingerOption optionValue)
{
- Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
+ Interop.Winsock.Linger lngopt = default;
lngopt.OnOff = optionValue.Enabled ? (ushort)1 : (ushort)0;
lngopt.Time = (ushort)optionValue.LingerTime;
public static SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption optionValue)
{
- Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
+ Interop.Winsock.IPMulticastRequest ipmr = default;
int optlen = Interop.Winsock.IPMulticastRequest.Size;
// This can throw ObjectDisposedException.
public static SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
{
- Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
+ Interop.Winsock.IPv6MulticastRequest ipmr = default;
int optlen = Interop.Winsock.IPv6MulticastRequest.Size;
public static SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption optionValue)
{
- Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
+ Interop.Winsock.Linger lngopt = default;
int optlen = 4;
// This can throw ObjectDisposedException.
IntPtr rawHandle = handle.DangerousGetHandle();
IntPtr* fileDescriptorSet = stackalloc IntPtr[2] { (IntPtr)1, rawHandle };
- Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
+ Interop.Winsock.TimeValue IOwait = default;
// A negative timeout value implies an indefinite wait.
int socketCount;
{
if (microseconds != -1)
{
- Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
+ Interop.Winsock.TimeValue IOwait = default;
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
private readonly bool _useSimpleDictionaryFormat;
public XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
- : base(null, int.MaxValue, new StreamingContext(), true)
+ : base(null, int.MaxValue, default(StreamingContext), true)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.KnownTypes;
}
internal XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
- : base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false)
+ : base(serializer, serializer.MaxItemsInObjectGraph, default(StreamingContext), false)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.knownTypeList;
private readonly bool _useSimpleDictionaryFormat;
public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
- : base(null, int.MaxValue, new StreamingContext(), true)
+ : base(null, int.MaxValue, default(StreamingContext), true)
{
_jsonSerializer = serializer;
}
internal XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
- : base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false)
+ : base(serializer, serializer.MaxItemsInObjectGraph, default(StreamingContext), false)
{
_emitXsiType = serializer.EmitTypeInformation;
this.rootTypeDataContract = rootTypeDataContract;
{
protected XmlObjectSerializer serializer;
protected DataContract rootTypeDataContract;
- internal ScopedKnownTypes scopedKnownTypes = new ScopedKnownTypes();
+ internal ScopedKnownTypes scopedKnownTypes;
protected DataContractDictionary serializerKnownDataContracts;
private bool _isSerializerKnownDataContractsSetExplicit;
protected IList<Type> serializerKnownTypeList;
internal XmlObjectSerializerContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
: this(serializer,
serializer.MaxItemsInObjectGraph,
- new StreamingContext(),
+ default(StreamingContext),
serializer.IgnoreExtensionDataObject,
dataContractResolver
)
internal class XmlObjectSerializerWriteContext : XmlObjectSerializerContext
#endif
{
- private ObjectReferenceStack _byValObjectsInScope = new ObjectReferenceStack();
+ private ObjectReferenceStack _byValObjectsInScope;
private XmlSerializableWriter _xmlSerializableWriter;
private const int depthToCheckCyclicReference = 512;
private ObjectToIdCache _serializedObjects;
}
else
{
- var pathSegments = new ArrayBuilder<string>();
+ ArrayBuilder<string> pathSegments = default;
int current = 0;
while (current < path.Length)
{
private sealed class ContentReader
{
- private readonly NamespaceCache _eCache = new NamespaceCache();
- private readonly NamespaceCache _aCache = new NamespaceCache();
+ private readonly NamespaceCache _eCache;
+ private readonly NamespaceCache _aCache;
private readonly IXmlLineInfo _lineInfo;
private XContainer _currentContainer;
private string _baseUri;
{
if (await reader.MoveToContentAsync().ConfigureAwait(false) != XmlNodeType.Element) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ExpectedNodeType, XmlNodeType.Element, reader.NodeType));
- XElement e = new XElement(new AsyncConstructionSentry());
+ XElement e = new XElement(default(AsyncConstructionSentry));
await e.ReadElementFromAsync(reader, options, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
public ElementWriter(XmlWriter writer)
{
_writer = writer;
- _resolver = new NamespaceResolver();
+ _resolver = default;
}
public void WriteElement(XElement e)
_writer = w;
_element = null;
_attributes = new List<XAttribute>();
- _resolver = new NamespaceResolver();
+ _resolver = default;
}
private void FlushElement()
public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
if (node == null) throw new ArgumentNullException(nameof(node));
- return new XPathEvaluator().Evaluate<object>(node, expression, resolver);
+ return default(XPathEvaluator).Evaluate<object>(node, expression, resolver);
}
/// <summary>
public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
if (node == null) throw new ArgumentNullException(nameof(node));
- return (IEnumerable<XElement>)new XPathEvaluator().Evaluate<XElement>(node, expression, resolver);
+ return (IEnumerable<XElement>)default(XPathEvaluator).Evaluate<XElement>(node, expression, resolver);
}
private static XText CalibrateText(XText n)
runningPositions = new List<RangePositionInfo>();
context.RunningPositions = runningPositions;
}
- RangePositionInfo rposInfo = new RangePositionInfo();
+ RangePositionInfo rposInfo = default;
rposInfo.curpos = _firstpos.Clone();
rposInfo.rangeCounters = new decimal[_minMaxNodesCount];
rposInfo = runningPositions[j];
if (matchCount + 2 >= runningPositions.Count)
{
- runningPositions.Add(new RangePositionInfo());
- runningPositions.Add(new RangePositionInfo());
+ runningPositions.Add(default(RangePositionInfo));
+ runningPositions.Add(default(RangePositionInfo));
}
RangePositionInfo newRPosInfo = runningPositions[matchCount];
if (newRPosInfo.rangeCounters == null)
bool schemasLockObtained = false;
try
{
- SpinWait spinner = new SpinWait();
+ SpinWait spinner = default;
while (true)
{
Monitor.TryEnter(InternalSyncObject, ref thisLockObtained);
/// </summary>
public XsdDateTime(string text, XsdDateTimeFlags kinds) : this()
{
- Parser parser = new Parser();
+ Parser parser = default;
if (!parser.Parse(text, kinds))
{
throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, text, kinds));
internal static bool TryParse(string text, XsdDateTimeFlags kinds, out XsdDateTime result)
{
- Parser parser = new Parser();
+ Parser parser = default;
if (!parser.Parse(text, kinds))
{
- result = new XsdDateTime();
+ result = default;
return false;
}
result = new XsdDateTime(parser);
int value, pos, numDigits;
Parts parts = Parts.HasNone;
- result = new XsdDuration();
+ result = default;
s = s.Trim();
length = s.Length;
char[] chars = value.ToCharArray();
int charsLength = chars.Length;
- SoapArrayInfo soapArrayInfo = new SoapArrayInfo();
+ SoapArrayInfo soapArrayInfo = default;
// Parse backwards to get length first, then optional dimensions, then qname.
int pos = charsLength - 1;
private SoapArrayInfo ParseSoap12ArrayType(string itemType, string arraySize)
{
- SoapArrayInfo soapArrayInfo = new SoapArrayInfo();
+ SoapArrayInfo soapArrayInfo = default;
if (itemType != null && itemType.Length > 0)
soapArrayInfo.qname = itemType;
#pragma warning restore 0414
private readonly Type _primitiveType;
private XmlMapping _mapping;
- private XmlDeserializationEvents _events = new XmlDeserializationEvents();
+ private XmlDeserializationEvents _events;
internal string DefaultNamespace = null;
private Type _rootType;
private bool _isReflectionBasedSerializer = false;
/// </summary>
public static StorageDescriptor None()
{
- return new StorageDescriptor();
+ return default;
}
/// <summary>
/// </summary>
public static StorageDescriptor Stack(Type itemStorageType, bool isCached)
{
- StorageDescriptor storage = new StorageDescriptor();
+ StorageDescriptor storage = default;
storage._location = ItemLocation.Stack;
storage._itemStorageType = itemStorageType;
storage._isCached = isCached;
/// </summary>
public static StorageDescriptor Parameter(int paramIndex, Type itemStorageType, bool isCached)
{
- StorageDescriptor storage = new StorageDescriptor();
+ StorageDescriptor storage = default;
storage._location = ItemLocation.Parameter;
storage._locationObject = paramIndex;
storage._itemStorageType = itemStorageType;
typeof(IList<>).MakeGenericType(itemStorageType).IsAssignableFrom(loc.LocalType),
"Type " + itemStorageType + " does not match the local variable's type");
- StorageDescriptor storage = new StorageDescriptor();
+ StorageDescriptor storage = default;
storage._location = ItemLocation.Local;
storage._locationObject = loc;
storage._itemStorageType = itemStorageType;
Debug.Assert(locIter.LocalType.GetMethod("get_Current").ReturnType == itemStorageType,
"Type " + itemStorageType + " does not match type of Current property.");
- StorageDescriptor storage = new StorageDescriptor();
+ StorageDescriptor storage = default;
storage._location = ItemLocation.Current;
storage._locationObject = locIter;
storage._itemStorageType = itemStorageType;
typeof(IList<>).MakeGenericType(itemStorageType).IsAssignableFrom(methGlobal.ReturnType),
"Type " + itemStorageType + " does not match the global method's return type");
- StorageDescriptor storage = new StorageDescriptor();
+ StorageDescriptor storage = default;
storage._location = ItemLocation.Global;
storage._locationObject = methGlobal;
storage._itemStorageType = itemStorageType;
if (AllowReplace(XmlILOptimization.EliminateStrConcat, local0))
{
// Concatenate all constant arguments
- StringConcat concat = new StringConcat();
+ StringConcat concat = default;
concat.Delimiter = local3;
foreach (QilLiteral lit in local2)
/// </remarks>
protected override QilNode VisitOr(QilBinary ndOr)
{
- Label lblTemp = new Label();
+ Label lblTemp = default;
// Visit left branch
switch (_iterCurr.CurrentBranchingContext)
/// </remarks>
protected override QilNode VisitNot(QilUnary ndNot)
{
- Label lblTemp = new Label();
+ Label lblTemp = default;
// Visit operand
// Reverse branch types
private void Sequence(QilList ndSeq)
{
LocalBuilder locIdx, locList;
- Label lblStart, lblNext, lblOnEnd = new Label();
+ Label lblStart, lblNext, lblOnEnd = default;
Label[] arrSwitchLabels;
int i;
Type itemStorageType = GetItemStorageType(ndSeq);
// By default, do not create a new iteration label
hasOnEnd = false;
- lblOnEnd = new Label();
+ lblOnEnd = default;
// If loop is not involved in Xml construction, or if loop returns exactly one value, then do nothing
if (!info.PushToWriterLast || nd.XmlType.IsSingleton)
/// </summary>
public void Create(XPathNavigator context, XmlNavigatorFilter filter, bool orSelf)
{
- AncestorIterator wrapped = new AncestorIterator();
+ AncestorIterator wrapped = default;
wrapped.Create(context, filter, orSelf);
_stack.Reset();
/// </summary>
public void Create(XPathNavigator context, XmlNavigatorFilter filter)
{
- XPathPrecedingDocOrderIterator wrapped = new XPathPrecedingDocOrderIterator();
+ XPathPrecedingDocOrderIterator wrapped = default;
wrapped.Create(context, filter);
_stack.Reset();
Uri collationUri;
CultureInfo cultInfo = null;
- Options options = new Options();
+ Options options = default;
if (throwOnError)
{
_invkGen = new InvokeGenerator(_f, debug);
_matcherBuilder = new MatcherBuilder(_f, _refReplacer, _invkGen);
_singlFocus = new SingletonFocus(_f);
- _funcFocus = new FunctionFocus();
+ _funcFocus = default;
_curLoop = new LoopFocus(_f);
_strConcat = new QilStrConcatenator(_f);
_varHelper = new VariableHelper(_f);
{
string keyName = (QilLiteral)name;
- _compiler.ParseQName(keyName, out string prefix, out string local, new ThrowErrorHelper());
+ _compiler.ParseQName(keyName, out string prefix, out string local, default(ThrowErrorHelper));
string nsUri = ResolvePrefixThrow(/*ignoreDefaultNs:*/true, prefix);
QilName qname = _f.QName(local, nsUri, prefix);
private XmlQualifiedName ResolveQNameThrow(bool ignoreDefaultNs, QilNode qilName)
{
string name = (QilLiteral)qilName;
- _compiler.ParseQName(name, out string prefix, out string local, new ThrowErrorHelper());
+ _compiler.ParseQName(name, out string prefix, out string local, default(ThrowErrorHelper));
string nsUri = ResolvePrefixThrow(/*ignoreDefaultNs:*/ignoreDefaultNs, prefix);
return new XmlQualifiedName(local, nsUri);
funcFlags = XslFlags.AnyType;
if (_compiler.Settings.EnableScript && ns != null)
{
- XmlExtensionFunction scrFunc = _compiler.Scripts.ResolveFunction(name, ns, args.Count, new NullErrorHelper());
+ XmlExtensionFunction scrFunc = _compiler.Scripts.ResolveFunction(name, ns, args.Count, default(NullErrorHelper));
if (scrFunc != null)
{
XmlQueryType xt = scrFunc.XmlReturnType;
}
}
- private StringConcat _strConcat = new StringConcat();
+ private StringConcat _strConcat;
// returns false if attribute is actualy namespace
private bool ReadAttribute(ref Record rec)
byte[] givenArray = array;
array = null;
- var union = new ByteArrayUnion();
+ ByteArrayUnion union = default;
union.UnderlyingArray = givenArray;
return union.ImmutableArray;
}
/// <returns>The underlying array, or null if <see cref="ImmutableArray{T}.IsDefault"/> is true.</returns>
internal static byte[] DangerousGetUnderlyingArray(ImmutableArray<byte> array)
{
- var union = new ByteArrayUnion();
+ ByteArrayUnion union = default;
union.ImmutableArray = array;
return union.UnderlyingArray;
}
{
MetadataReader reader = Reader;
- InternalManifestResourceInfo result = new InternalManifestResourceInfo();
+ InternalManifestResourceInfo result = default;
ManifestResourceHandleCollection manifestResources = reader.ManifestResources;
foreach (ManifestResourceHandle resourceHandle in manifestResources)
{
Debug.Assert(types != null);
QueryResult<ConstructorInfo> queryResult = Query<ConstructorInfo>(bindingAttr);
- ListBuilder<ConstructorInfo> candidates = new ListBuilder<ConstructorInfo>();
+ ListBuilder<ConstructorInfo> candidates = default;
foreach (ConstructorInfo candidate in queryResult)
{
if (candidate.QualifiesBasedOnParameterCount(bindingAttr, callConvention, types))
{
// Group #2: This group of api takes a set of parameter types and an optional binder.
QueryResult<MethodInfo> queryResult = Query<MethodInfo>(name, bindingAttr);
- ListBuilder<MethodInfo> candidates = new ListBuilder<MethodInfo>();
+ ListBuilder<MethodInfo> candidates = default;
foreach (MethodInfo candidate in queryResult)
{
if (genericParameterCount != GenericParameterCountAny && genericParameterCount != candidate.GetGenericParameterCount())
{
// Group #2: This group of api takes a set of parameter types, a return type (both cannot be null) and an optional binder.
QueryResult<PropertyInfo> queryResult = Query<PropertyInfo>(name, bindingAttr);
- ListBuilder<PropertyInfo> candidates = new ListBuilder<PropertyInfo>();
+ ListBuilder<PropertyInfo> candidates = default;
foreach (PropertyInfo candidate in queryResult)
{
if (types == null || (candidate.GetIndexParameters().Length == types.Length))
{
fixed (char* overrideDigits = digits)
{
- var numberBuffer = new Number.NumberBuffer();
+ Number.NumberBuffer numberBuffer = default;
numberBuffer.overrideDigits = overrideDigits + startIndex;
numberBuffer.precision = precision;
numberBuffer.scale = scale;
out bool sign
)
{
- FormatProvider.Number.NumberBuffer numberBuffer = new FormatProvider.Number.NumberBuffer();
+ FormatProvider.Number.NumberBuffer numberBuffer = default;
unsafe
{
public static BigNumberBuffer Create()
{
- BigNumberBuffer number = new BigNumberBuffer();
+ BigNumberBuffer number = default;
number.digits = new StringBuilder();
return number;
}
{
get
{
- Duration duration = new Duration();
+ Duration duration = default;
duration._durationType = DurationType.Automatic;
return duration;
{
get
{
- Duration duration = new Duration();
+ Duration duration = default;
duration._durationType = DurationType.Forever;
return duration;
throw new ArgumentOutOfRangeException(nameof(timeSpan));
}
- KeyTime keyTime = new KeyTime();
+ KeyTime keyTime = default;
keyTime._timeSpan = timeSpan;
{
get
{
- RepeatBehavior forever = new RepeatBehavior();
+ RepeatBehavior forever = default;
forever.Type = RepeatBehaviorType.Forever;
return forever;
private static Matrix CreateIdentity()
{
- Matrix matrix = new Matrix();
+ Matrix matrix = default;
matrix.SetMatrix(1, 0,
0, 1,
0, 0);
public static Matrix3D operator *(Matrix3D matrix1, Matrix3D matrix2)
{
- Matrix3D matrix3D = new Matrix3D();
+ Matrix3D matrix3D = default;
matrix3D.M11 = matrix1.M11 * matrix2.M11 +
matrix1.M12 * matrix2.M21 +
private static Matrix3D CreateIdentity()
{
- Matrix3D matrix3D = new Matrix3D();
+ Matrix3D matrix3D = default;
matrix3D.SetMatrix(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
private static Rect CreateEmptyRect()
{
- Rect rect = new Rect();
+ Rect rect = default;
// TODO: for consistency with width/height we should change these
// to assign directly to the backing fields.
private static Size CreateEmptySize()
{
- Size size = new Size();
+ Size size = default;
// We can't set these via the property setters because negatives widths
// are rejected in those APIs.
size._width = float.NegativeInfinity;
public static Color FromArgb(byte a, byte r, byte g, byte b)
{
- Color c1 = new Color();
+ Color c1 = default;
c1.A = a;
c1.R = r;
newState.Privileges.Luid = this.luid;
newState.Privileges.Attributes = enable ? Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED : Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_DISABLED;
- Interop.Advapi32.TOKEN_PRIVILEGE previousState = new Interop.Advapi32.TOKEN_PRIVILEGE();
+ Interop.Advapi32.TOKEN_PRIVILEGE previousState = default;
uint previousSize = 0;
//
{
Interop.NCrypt.NCryptBuffer* buffers = stackalloc Interop.NCrypt.NCryptBuffer[3];
- Interop.NCrypt.PBE_PARAMS pbeParams = new Interop.NCrypt.PBE_PARAMS();
+ Interop.NCrypt.PBE_PARAMS pbeParams = default;
Span<byte> salt = new Span<byte>(pbeParams.rgbSalt, Interop.NCrypt.PBE_PARAMS.RgbSaltSize);
RandomNumberGenerator.Fill(salt);
pbeParams.Params.cbSalt = salt.Length;
/// </summary>
private static ECCurve Create(Oid oid)
{
- ECCurve curve = new ECCurve();
+ ECCurve curve = default;
curve.CurveType = ECCurveType.Named;
curve.Oid = oid;
return curve;
throw new ObjectDisposedException(nameof(ECDiffieHellmanPublicKey));
}
- ECParameters ecparams = new ECParameters();
+ ECParameters ecparams = default;
ECCng.ExportPrimeCurveParameters(ref ecparams, _keyBlob, includePrivateParameters: false);
return ecparams;
}
}
else
{
- ECParameters ecparams = new ECParameters();
+ ECParameters ecparams = default;
ECCng.ExportNamedCurveParameters(ref ecparams, _keyBlob, includePrivateParameters: false);
ecparams.Curve = ECCurve.CreateFromFriendlyName(_curveName);
return ecparams;
{
Interop.NCrypt.NCryptBuffer* buffers = stackalloc Interop.NCrypt.NCryptBuffer[3];
- Interop.NCrypt.PBE_PARAMS pbeParams = new Interop.NCrypt.PBE_PARAMS();
+ Interop.NCrypt.PBE_PARAMS pbeParams = default;
Span<byte> salt = new Span<byte>(pbeParams.rgbSalt, Interop.NCrypt.PBE_PARAMS.RgbSaltSize);
RandomNumberGenerator.Fill(salt);
pbeParams.Params.cbSalt = salt.Length;
{
using (CngKey key = Import())
{
- ECParameters ecparams = new ECParameters();
+ ECParameters ecparams = default;
byte[] blob = ECCng.ExportFullKeyBlob(key, includePrivateParameters: false);
ECCng.ExportPrimeCurveParameters(ref ecparams, blob, includePrivateParameters: false);
return ecparams;
{
using (CngKey key = Import())
{
- ECParameters ecparams = new ECParameters();
+ ECParameters ecparams = default;
string curveName = key.GetCurveName(out _);
if (string.IsNullOrEmpty(curveName))
byte bVersion;
ReadKeyBlobHeader(br, out bVersion);
- DSAParameters dsaParameters = new DSAParameters();
+ DSAParameters dsaParameters = default;
if (bVersion > 2)
{
uint expAsDword = br.ReadUInt32();
- RSAParameters rsaParameters = new RSAParameters();
+ RSAParameters rsaParameters = default;
rsaParameters.Exponent = ExponentAsBytes(expAsDword);
rsaParameters.Modulus = br.ReadReversed(modulusLength);
if (includePrivateParameters)
CmsRecipient recipient,
out bool v0Recipient)
{
- KeyTransRecipientInfoAsn ktri = new KeyTransRecipientInfoAsn();
+ KeyTransRecipientInfoAsn ktri = default;
if (recipient.RecipientIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier)
{
hasher.AppendData(data.Span);
byte[] dataHash = hasher.GetHashAndReset();
- SignerInfoAsn newSignerInfo = new SignerInfoAsn();
+ SignerInfoAsn newSignerInfo = default;
newSignerInfo.DigestAlgorithm.Algorithm = DigestAlgorithm;
// If the user specified attributes (not null, count > 0) we need attributes.
}
// Use the serializer/deserializer to DER-normalize the attribute order.
- SignedAttributesSet signedAttrsSet = new SignedAttributesSet();
+ SignedAttributesSet signedAttrsSet = default;
signedAttrsSet.SignedAttributes = PkcsHelpers.NormalizeAttributeSet(
signedAttrs.ToArray(),
normalized => hasher.AppendData(normalized));
bool hasPathLengthConstraint,
int pathLengthConstraint)
{
- BasicConstraintsAsn constraints = new BasicConstraintsAsn();
+ BasicConstraintsAsn constraints = default;
constraints.CA = certificateAuthority;
if (hasPathLengthConstraint)
// The CapiSha1 value is the SHA-1 of the SubjectPublicKeyInfo field, inclusive
// of the DER structural bytes.
- SubjectPublicKeyInfoAsn spki = new SubjectPublicKeyInfoAsn();
+ SubjectPublicKeyInfoAsn spki = default;
spki.Algorithm = new AlgorithmIdentifierAsn { Algorithm = key.Oid, Parameters = key.EncodedParameters.RawData };
spki.SubjectPublicKey = key.EncodedKeyValue.RawData;
// check to see if we can figure out what key number it needs to re-open.
int keySpec = GuessKeySpec(provider, keyName, machineKey, cngKey.AlgorithmGroup);
- CRYPT_KEY_PROV_INFO keyProvInfo = new CRYPT_KEY_PROV_INFO();
+ CRYPT_KEY_PROV_INFO keyProvInfo = default;
fixed (char* keyNamePtr = cngKey.KeyName)
fixed (char* provNamePtr = cngKey.Provider.Provider)
// Make a new pal from bytes.
CertificatePal pal = (CertificatePal)FromBlob(RawData, SafePasswordHandle.InvalidHandle, X509KeyStorageFlags.PersistKeySet);
- CRYPT_KEY_PROV_INFO keyProvInfo = new CRYPT_KEY_PROV_INFO();
+ CRYPT_KEY_PROV_INFO keyProvInfo = default;
fixed (char* keyName = keyContainerInfo.KeyContainerName)
fixed (char* provName = keyContainerInfo.ProviderName)
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
{
- CERT_CHAIN_PARA chainPara = new CERT_CHAIN_PARA();
+ CERT_CHAIN_PARA chainPara = default;
chainPara.cbSize = sizeof(CERT_CHAIN_PARA);
if (!Interop.crypt32.CertGetCertificateChain((IntPtr)ChainEngine.HCCE_CURRENT_USER, _certContext, (FILETIME*)null, SafeCertStoreHandle.InvalidHandle, ref chainPara, CertChainFlags.None, IntPtr.Zero, out certChainContext))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
using (SafeChainEngineHandle storeHandle = GetChainEngine(trustMode, customTrustStore, useMachineContext))
using (SafeCertStoreHandle extraStoreHandle = ConvertStoreToSafeHandle(extraStore))
{
- CERT_CHAIN_PARA chainPara = new CERT_CHAIN_PARA();
+ CERT_CHAIN_PARA chainPara = default;
chainPara.cbSize = Marshal.SizeOf<CERT_CHAIN_PARA>();
int applicationPolicyCount;
// Need to get a valid SafeCertStoreHandle otherwise the default stores will be trusted
using (SafeCertStoreHandle customTrustStoreHandle = ConvertStoreToSafeHandle(customTrustStore, true))
{
- CERT_CHAIN_ENGINE_CONFIG customChainEngine = new CERT_CHAIN_ENGINE_CONFIG();
+ CERT_CHAIN_ENGINE_CONFIG customChainEngine = default;
customChainEngine.cbSize = Marshal.SizeOf<CERT_CHAIN_ENGINE_CONFIG>();
customChainEngine.hExclusiveRoot = customTrustStoreHandle.DangerousGetHandle();
chainEngineHandle = Interop.crypt32.CertCreateCertificateChainEngine(ref customChainEngine);
unsafe
{
- CERT_CHAIN_POLICY_PARA para = new CERT_CHAIN_POLICY_PARA();
+ CERT_CHAIN_POLICY_PARA para = default;
para.cbSize = sizeof(CERT_CHAIN_POLICY_PARA);
para.dwFlags = (int)flags;
- CERT_CHAIN_POLICY_STATUS status = new CERT_CHAIN_POLICY_STATUS();
+ CERT_CHAIN_POLICY_STATUS status = default;
status.cbSize = sizeof(CERT_CHAIN_POLICY_STATUS);
if (!Interop.crypt32.CertVerifyCertificateChainPolicy(ChainPolicy.CERT_CHAIN_POLICY_BASE, _chain, ref para, ref status))
{
blobFormat = CngKeyBlobFormat.EccPublicBlob;
keyBlob = ExportKeyBlob(bCryptKeyHandle, blobFormat);
- ECParameters ecparams = new ECParameters();
+ ECParameters ecparams = default;
ExportNamedCurveParameters(ref ecparams, keyBlob, false);
ecparams.Curve = ECCurve.CreateFromFriendlyName(curveName);
ecdsa = new ECDsaCng();
Helpers.ValidateDer(signatureAlgorithmAsn.Parameters.Value);
}
- SubjectPublicKeyInfoAsn spki = new SubjectPublicKeyInfoAsn();
+ SubjectPublicKeyInfoAsn spki = default;
spki.Algorithm = new AlgorithmIdentifierAsn { Algorithm = PublicKey.Oid, Parameters = PublicKey.EncodedParameters.RawData };
spki.SubjectPublicKey = PublicKey.EncodedKeyValue.RawData;
{
SafeLsaPolicyHandle policyHandle;
- var attributes = new Interop.OBJECT_ATTRIBUTES();
+ Interop.OBJECT_ATTRIBUTES attributes = default;
uint error = Interop.Advapi32.LsaOpenPolicy(systemName, ref attributes, (int)rights, out policyHandle);
if (error == 0)
{
{
public abstract class CategoriesDocument : IExtensibleSyndicationObject
{
- private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private ExtensibleSyndicationObject _extensions;
internal CategoriesDocument()
{
private static IEnumerable<string> s_singleEmptyAccept;
private Collection<string> _accepts;
private Collection<CategoriesDocument> _categories;
- private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private ExtensibleSyndicationObject _extensions;
public ResourceCollectionInfo()
{
{
public class ServiceDocument : IExtensibleSyndicationObject
{
- private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private ExtensibleSyndicationObject _extensions;
private Collection<Workspace> _workspaces;
public ServiceDocument() : this(null)
// NOTE: This class implements Clone so if you add any members, please update the copy ctor
public class SyndicationCategory : IExtensibleSyndicationObject
{
- private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private ExtensibleSyndicationObject _extensions;
public SyndicationCategory() : this((string)null)
{
private Collection<SyndicationPerson> _authors;
private Collection<SyndicationCategory> _categories;
private Collection<SyndicationPerson> _contributors;
- private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private ExtensibleSyndicationObject _extensions;
private IEnumerable<SyndicationItem> _items;
private DateTimeOffset _lastUpdatedTime;
private Collection<SyndicationLink> _links;
private Collection<SyndicationPerson> _authors;
private Collection<SyndicationCategory> _categories;
private Collection<SyndicationPerson> _contributors;
- private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private ExtensibleSyndicationObject _extensions;
private DateTimeOffset _lastUpdatedTime;
private Collection<SyndicationLink> _links;
private DateTimeOffset _publishDate;
// NOTE: This class implements Clone so if you add any members, please update the copy ctor
public class SyndicationLink : IExtensibleSyndicationObject
{
- private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private ExtensibleSyndicationObject _extensions;
private long _length;
public SyndicationLink(Uri uri) : this(uri, null, null, null, 0)
// NOTE: This class implements Clone so if you add any members, please update the copy ctor
public class SyndicationPerson : IExtensibleSyndicationObject
{
- private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private ExtensibleSyndicationObject _extensions;
public SyndicationPerson() : this((string)null)
{
public class Workspace : IExtensibleSyndicationObject
{
private Collection<ResourceCollectionInfo> _collections;
- private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private ExtensibleSyndicationObject _extensions;
public Workspace()
{
/// </devdoc>
public class ServiceBase : Component
{
- private SERVICE_STATUS _status = new SERVICE_STATUS();
+ private SERVICE_STATUS _status;
private IntPtr _statusHandle;
private ServiceControlCallbackEx _commandCallbackEx;
private ServiceMainCallback _mainCallback;
{
using (var serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_QUERY_STATUS))
{
- Interop.Advapi32.SERVICE_STATUS svcStatus = new Interop.Advapi32.SERVICE_STATUS();
+ Interop.Advapi32.SERVICE_STATUS svcStatus = default;
bool success = Interop.Advapi32.QueryServiceStatus(serviceHandle, &svcStatus);
if (!success)
throw new Win32Exception(Marshal.GetLastWin32Error());
{
using (var serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_PAUSE_CONTINUE))
{
- Interop.Advapi32.SERVICE_STATUS status = new Interop.Advapi32.SERVICE_STATUS();
+ Interop.Advapi32.SERVICE_STATUS status = default;
bool result = Interop.Advapi32.ControlService(serviceHandle, Interop.Advapi32.ControlOptions.CONTROL_PAUSE, &status);
if (!result)
{
{
using (var serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_PAUSE_CONTINUE))
{
- Interop.Advapi32.SERVICE_STATUS status = new Interop.Advapi32.SERVICE_STATUS();
+ Interop.Advapi32.SERVICE_STATUS status = default;
bool result = Interop.Advapi32.ControlService(serviceHandle, Interop.Advapi32.ControlOptions.CONTROL_CONTINUE, &status);
if (!result)
{
{
using (var serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_USER_DEFINED_CONTROL))
{
- Interop.Advapi32.SERVICE_STATUS status = new Interop.Advapi32.SERVICE_STATUS();
+ Interop.Advapi32.SERVICE_STATUS status = default;
bool result = Interop.Advapi32.ControlService(serviceHandle, command, &status);
if (!result)
{
throw;
}
- GCHandle argPtrsHandle = new GCHandle();
+ GCHandle argPtrsHandle = default;
try
{
argPtrsHandle = GCHandle.Alloc(argPtrs, GCHandleType.Pinned);
}
}
- Interop.Advapi32.SERVICE_STATUS status = new Interop.Advapi32.SERVICE_STATUS();
+ Interop.Advapi32.SERVICE_STATUS status = default;
bool result = Interop.Advapi32.ControlService(serviceHandle, Interop.Advapi32.ControlOptions.CONTROL_STOP, &status);
if (!result)
{
/// <returns>"true" if successfully parsed.</returns>
private static bool TryParseDateTimeOffset(ReadOnlySpan<byte> source, out DateTimeParseData parseData)
{
+ parseData = default;
+
// Source does not have enough characters for YYYY-MM-DD
if (source.Length < 10)
{
- parseData = default;
return false;
}
// just [year]["-"][month] (a) and just [year] (b), but we currently
// don't permit it.
- parseData = new DateTimeParseData();
-
{
uint digit1 = source[0] - (uint)'0';
uint digit2 = source[1] - (uint)'0';
//current head is empty and it is NOT the last segment,
//it means another thread is growing new segment
{
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
while (head.IsEmpty)
{
if (head.Next == null)
tail = _tail;
headLow = head.Low;
tailHigh = tail.High;
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
//we loop until the observed values are stable and sensible.
//This ensures that any update order by other methods can be tolerated.
{
try
{
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
if (head == tail)
{
/// </param>
public void Enqueue(T item)
{
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
while (true)
{
Segment tail = _tail;
/// <returns>return false only if the current segment is empty</returns>
internal bool TryRemove(out T result)
{
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
int lowLocal = Low, highLocal = High;
while (lowLocal <= highLocal)
{
{
//if the specified value is not available (this spot is taken by a push operation,
// but the value is not written into yet), then spin
- SpinWait spinLocal = new SpinWait();
+ SpinWait spinLocal = default;
while (!_state[lowLocal]._value)
{
spinLocal.SpinOnce();
//while the *current* thread is doing *this* Dequeue operation, and finds that it needs to
//dispose the current (and ONLY) segment. Then we need to wait till thread A finishes its
//Grow operation, this is the reason of having the following while loop
- spinLocal = new SpinWait();
+ spinLocal = default;
while (_next == null)
{
spinLocal.SpinOnce();
int lowLocal = Low;
if (lowLocal > High)
return false;
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
while (!_state[lowLocal]._value)
{
spin.SpinOnce();
{
for (int i = start; i <= end; i++)
{
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
while (!_state[i]._value)
{
spin.SpinOnce();
"thread local functions should only be supplied for loops w/ thread local bodies");
// Instantiate our result. Specifics will be filled in later.
- ParallelLoopResult result = new ParallelLoopResult();
+ ParallelLoopResult result = default;
// We just return immediately if 'to' is smaller (or equal to) 'from'.
if (toExclusive <= fromInclusive)
"thread local functions should only be supplied for loops w/ thread local bodies");
// Instantiate our result. Specifics will be filled in later.
- ParallelLoopResult result = new ParallelLoopResult();
+ ParallelLoopResult result = default;
// We just return immediately if 'to' is smaller (or equal to) 'from'.
if (toExclusive <= fromInclusive)
ParallelLoopStateFlags64 sharedPStateFlags = new ParallelLoopStateFlags64();
// Instantiate our result. Specifics will be filled in later.
- ParallelLoopResult result = new ParallelLoopResult();
+ ParallelLoopResult result = default;
// Keep track of any cancellations
OperationCanceledException? oce = null;
int oldLBI = pflags._lowestBreakIteration;
if (iteration < oldLBI)
{
- SpinWait wait = new SpinWait();
+ SpinWait wait = default;
while (Interlocked.CompareExchange(
ref pflags._lowestBreakIteration,
iteration,
long oldLBI = pflags.LowestBreakIteration;
if (iteration < oldLBI)
{
- SpinWait wait = new SpinWait();
+ SpinWait wait = default;
while (Interlocked.CompareExchange(
ref pflags._lowestBreakIteration,
iteration,
internal bool AtomicLoopStateUpdate(int newState, int illegalStates, ref int oldState)
{
- SpinWait sw = new SpinWait();
+ SpinWait sw = default;
do
{
throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA);
}
- SpinWait spinner = new SpinWait();
+ SpinWait spinner = default;
long newPhase = 0;
while (true)
{
throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA);
}
- SpinWait spinner = new SpinWait();
+ SpinWait spinner = default;
while (true)
{
int currentTotal = _currentTotalCount;
/// disposed.</exception>
public void SignalAndWait()
{
- SignalAndWait(new CancellationToken());
+ SignalAndWait(CancellationToken.None);
}
/// <summary>
/// disposed.</exception>
public bool SignalAndWait(TimeSpan timeout)
{
- return SignalAndWait(timeout, new CancellationToken());
+ return SignalAndWait(timeout, CancellationToken.None);
}
/// <summary>
/// disposed.</exception>
public bool SignalAndWait(int millisecondsTimeout)
{
- return SignalAndWait(millisecondsTimeout, new CancellationToken());
+ return SignalAndWait(millisecondsTimeout, CancellationToken.None);
}
/// <summary>
int current;
int currentTotal;
long phase;
- SpinWait spinner = new SpinWait();
+ SpinWait spinner = default;
while (true)
{
currentTotal = _currentTotalCount;
//1- The event is set
//2- the phase count is incremented more than one time, this means the next phase is finished as well,
//but the event will be reset again, so we check the phase count instead
- SpinWait spinner = new SpinWait();
+ SpinWait spinner = default;
while (!currentPhaseEvent.IsSet && CurrentPhaseNumber - observedPhase <= 1)
{
spinner.SpinOnce();
Debug.Assert(_event != null);
int observedCount;
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
while (true)
{
observedCount = _currentCount;
// Loop around until we successfully increment the count.
int observedCount;
- SpinWait spin = new SpinWait();
+ SpinWait spin = default;
while (true)
{
observedCount = _currentCount;
/// disposed.</exception>
public void Wait()
{
- Wait(Timeout.Infinite, new CancellationToken());
+ Wait(Timeout.Infinite, CancellationToken.None);
}
throw new ArgumentOutOfRangeException(nameof(timeout));
}
- return Wait((int)totalMilliseconds, new CancellationToken());
+ return Wait((int)totalMilliseconds, CancellationToken.None);
}
/// <summary>
/// disposed.</exception>
public bool Wait(int millisecondsTimeout)
{
- return Wait(millisecondsTimeout, new CancellationToken());
+ return Wait(millisecondsTimeout, CancellationToken.None);
}
/// <summary>
throw GetInvalidTimeoutException(nameof(millisecondsTimeout));
}
- var lockCookie = new LockCookie();
+ LockCookie lockCookie = default;
int threadID = GetCurrentThreadID();
lockCookie._threadID = threadID;
public LockCookie ReleaseLock()
{
- var lockCookie = new LockCookie();
+ LockCookie lockCookie = default;
int threadID = GetCurrentThreadID();
lockCookie._threadID = threadID;
/// </summary>
internal readonly struct EnlistmentTraceIdentifier : IEquatable<EnlistmentTraceIdentifier>
{
- public static readonly EnlistmentTraceIdentifier Empty = new EnlistmentTraceIdentifier();
+ public static readonly EnlistmentTraceIdentifier Empty = default;
public EnlistmentTraceIdentifier(
Guid resourceManagerIdentifier,
}
// Just create a new transaction.
- TransactionOptions options = new TransactionOptions();
+ TransactionOptions options = default;
options.IsolationLevel = tx._outcomeSource._isoLevel;
options.Timeout = newTimeout;
/// </summary>
internal readonly struct TransactionTraceIdentifier : IEquatable<TransactionTraceIdentifier>
{
- public static readonly TransactionTraceIdentifier Empty = new TransactionTraceIdentifier();
+ public static readonly TransactionTraceIdentifier Empty = default;
public TransactionTraceIdentifier(string transactionIdentifier, int cloneIdentifier)
{
culture = CultureInfo.CurrentCulture;
}
- ValueStringBuilder sb = new ValueStringBuilder();
+ ValueStringBuilder sb = default;
sb.Append(font.Name);
sb.Append(culture.TextInfo.ListSeparator[0] + " ");
sb.Append(font.Size.ToString(culture.NumberFormat));